Unnecessary usage of virtual functions just for code reuse - c++

I'm using inheritance only for the sake of code reuse, I never cast class to its base class. It is performance heavy program so I would like to avoid the use of virtual functions but I do not know how. Consider following code
class A{
public:
void print(){
std::cout << "Result of f() is: " << f() << std::endl;
}
virtual std::string f(){
return "A";
}
};
class B : public A{
public:
virtual std::string f(){
return "B";
}
};
Would it be somehow possible to not use virtual function for function f() and not to reimplement function print() in the class B? I do not care that A is base class of B I just do not want to write down f() again. Probably inheritance is not the way to go, maybe templates can be used in smart way but I have no idea.

The CRTP pattern is typically used to avoid dynamic dispatch when it can be statically determined what implementation method to call for a particular method.
In your example, both A and B would inherit from a single base class, which provides the print() method. The base class, let's call it Print, is a template whose template argument is a class that provides f(). The twist that earned this pattern the "curious" moniker is that the subclasses must inherit the base class templatized over the subclass. This allows the subclasses to access the base class's print method, but obtaining a version of the base class - and by extension the version of print - that invokes their own f.
Here is an example of working code:
#include <iostream>
template<typename F>
class Print {
public:
void print() {
F& final = static_cast<F&>(*this);
std::cout << "Result of f() is: " << final.f() << std::endl;
}
};
class A: public Print<A> {
public:
std::string f(){
return "A";
}
};
class B: public Print<B> {
public:
std::string f(){
return "B";
}
};
int main() {
A a;
B b;
a.print();
b.print();
}
Although the print implementation is reused among A and B, there are no virtual methods here, nor is there virtual (run-time) dispatch or run-time checks. The one cast present is a static_cast<> whose safety is duly verified by the compiler.
This is possible because for every use of Print<F>, the compiler knows exactly what F is. Thus Print<A>::print is known to invoke A::f, while Print<B>::print invokes B::f, all known at compile time. This enables the compiler to inline and otherwise optimize such calls just like any other non-virtual method calls.
The downside is that there is no inheritance, either. Note that B is not derived from A - if it were, the pattern wouldn't work and both A::print and B::print would print A, since that's what Print<A> outputs. More fundamentally, you cannot pass B* where an A* is expected - that's undefined behavior. In fact, A and B don't share any common superclass, the Parent<A> and Parent<B> classes are completely separate. Loss of run-time dispatch, with both its drawbacks and benefits, and enabling static dispatch instead, is a fundamental tradeoff of static polymorphism.

If, for whatever reason, you do not want the "overhead" of dynamic binding, you can omit the virtual-keyword, which makes the compiler use static binding and disabling polymorphism. That is, the compiler will bind the implementation solely based on the type of the variable at compile time, not at run time.
To be honest, I never were in the situation where I defined a specific implementation for a method in a subclass without enabling polymorphism. Doing so usually indicates that there is no specific behaviour, i.e. the method should not be overridden in the subclass at all.
Further, already the code encapsulating a character constant into a string object costs far more performance then the dynamic binding / vtable-"overhead". Really, rethink it twice and then measure the performance increase before doing such "optimisations".
Anyway, see how your code behaves if you omit virtual. Note that ptr->f() in the code is bound to A::f, because the type of the variable is A*, though it points to an object of type B:
class A{
public:
void print(){
std::cout << "Result of f() is: " << f() << std::endl;
}
std::string f(){
return "A";
}
};
class B : public A{
public:
std::string f(){
return "B";
}
};
int main()
{
A a; cout << a.f(); // -> yields "A"
B b; cout << b.f(); // -> yields "B"
A* ptr = &b; cout << ptr->f(); // -> yields "A"; (virtual f, in contrast) would be "B"
return 0;
}

You could use templates to select dynamic or non-dynamic versions of A and B. A rather tricky/ugly option but worth considering.
#include <string>
template <bool Virt = false>
class A{
public:
std::string f(){
return "A";
}
};
template <>
class A<true> : A<false>{
public:
virtual std::string f(){
return A<false>::f();
}
};
template <bool Virt = false>
class B : public A<Virt>{
public:
std::string f(){
return "B";
}
};
std::string f1() { return B<>().f(); }
std::string f2(A<true> &a) { return a.f(); }
std::string f3() { B<true> b; return f2(b); }
#include <iostream>
int main(){
std::cout << f1() << '\n';
std::cout << f3() << '\n';
return(0);
}
An interesting point to note with this, it would not be possible except for the debatable decision made very early on in C++ (pre-templates) that the virtual keyword should be optional when overriding.

Related

c++: Is a multiple inheritance from template class and general class valid?

I'm trying to figure out why b->boo() actually calls a.far().
is the multiple inheritance from template class and general class forbidden? why does the inherit order matter?
The code is here:
#include <iostream>
template <int somecount>
class inner_parent_class
{
public:
int array[somecount];
virtual void far() = 0;
};
class any_class
{
public:
virtual void boo() = 0;
};
template <int somecount>
class child_class_bad : public inner_parent_class<somecount>, public any_class
{
public:
virtual void boo() override
{
std::cout << "call me" << std::endl;
}
virtual void far() override
{
std::cout << "do not call me" << std::endl;
}
};
template <int somecount>
class child_class_good : public any_class, public inner_parent_class<somecount>
{
public:
virtual void boo() override
{
std::cout << "call me" << std::endl;
}
virtual void far() override
{
std::cout << "do not call me" << std::endl;
}
};
int main()
{
{
child_class_good<32> a;
any_class* b;
auto c = dynamic_cast<void*>(&a);
b = reinterpret_cast<any_class*>(c);
b->boo();
}
{
child_class_bad<32> a;
any_class* b;
auto c = dynamic_cast<void*>(&a);
b = reinterpret_cast<any_class*>(c);
b->boo();
}
return 0;
}
# GCC 9.3.0
# VS 2019 16.5.3
I suppose that both child classes (child_class_good and child_class_bad) are different classes even though their class names are the same, because they are template classes and constructed separately at compiled time. Nevertheless, each class might have its own v-table, so I think calling boo() as their common parent class any_class should correctly work.
reinterpret_cast cannot be used to do what you're trying to do. A reinterpret_cast from a void* to a T* only produces a pointer to a valid T* if the void* pointer it was given was a pointer to an object of type T.
Doing a dynamic_cast<void*>(p) returns a void* which points to the most-derived object pointed to by p. Since your &a is in fact the most-derived object that it points to, it simply converts the pointer to a void*.
Then you perform reinterpret_cast<any_class*> on that void*. The void* points to an object of type child_class_good<32> or child_class_bad<32>. Your cast is saying that the pointer actually points to an any_class. This is incorrect (neither type is standard layout, so the layout of the base classes is not defined), and thus attempting to use the results will yield undefined behavior.
The case that you identify as good is just as invalid as bad; it merely happens to work.
It is not clear why you're trying to do whatever it is you're trying to do, but there's no valid way to take a void* pointing to the most-derived object of an unknown type and casting it to anything useful. In order to use a void*, you have to know the exact type that was used to produce that void*.

Creating a subclass to affect the behavior of another subclass

The library I am using defines an abstract base class A with ~10 pure virtual methods. There are no non-pure methods publicly defined and I suspect that A has no private data, i.e. the class is merely an interface. The library also defines a few concrete sub-classes of A, such as C.
I would like to add some functionality to A so that all of its sub-classes inherit this functionality. However, A is defined in the library and I cannot do this.
Instead, I have defined a new sub-class of B. This sub-class is not concrete and all of the pure virtual methods of A are left alone. It defines a few new helper methods that call out to the methods defined by A. There are also no fields defined by B.
In order to use B to augment the functionality of instance of C I have done the following, which I suspect is not guaranteed behavior.
Create an object of type C on the heap.
Cast the pointer to this object to instead be of type B*.
Return this pointer, exiting the local scope where the object was created.
Call methods defined by B using this pointer in a different scope.
Is this safe? The objects are created on the heap, so I don't think any slicing will happen. If the safety depends on which fields A and C define, what requirements are needed to guarantee this behavior?
If neither A nor C had their own data other than the vpointer, would this be safe?
What about if only C has its own data?
Edit: I should add that I have attempted this and the behavior has at least seemed to be what I want. I have not profiled for memory leaks though.
The whole thing looks like code smell to me. I would take the approach for B class of a wrapper class: take an A* pointer in the constructor, forwarding the calls you need to that A*. Then you can pass a C* to that constructor, that will be correctly deleted through a "delete" in B destructor.
Here is one idea following up on my comment. It behaves as intended, might be some hidden dangers but to me it seems reasonable as long as bar does not hold any data.
#include <iostream>
struct base {
int x = 1;
int y = 2;
void show() {
std::cout << x + y << std::endl;
}
virtual void virt() = 0;
};
struct foo : base {
int a = 5;
int b = 2;
void print() {
std::cout << a + b << std::endl;
x++;
}
void virt() override {
std::cout << "foo" << std::endl;
}
};
template <typename T>
struct bar : T {
void print2() {
std::cout << T::a * T::b << std::endl;
T::b++;
T::x++;
T::virt();
}
};
template <typename Base>
bar<Base>* extend_with_bar(Base& base) {
return static_cast<bar<Base>*>(&base);
}
int main() {
foo f;
f.show();
f.print();
auto b = extend_with_bar(f);
b->print2();
b->print2();
b->print();
f.print();
b->show();
f.show();
b->virt();
}

Ensure safety while using CRTP

Consider following snippet of code making using of CRTP
#include <iostream>
struct Alone
{
Alone() { std::cout << "Alone constructor called" << std::endl; }
int me {10};
};
struct Dependant
{
explicit Dependant(const Alone& alone)
: ref_alone(alone)
{ std::cout << "Dependant called with alone's me = " << alone.me << std::endl; }
const Alone& ref_alone;
void print() { std::cout << ref_alone.me << std::endl; }
};
template <typename D>
struct Base
{
Base() { std::cout << "Base constructor called" << std::endl; }
D* getDerived() { return static_cast<D*>(this); }
Dependant f { getDerived()->alone };
void print() { f.print(); }
};
struct Derived : Base <Derived>
{
Derived() { std::cout << "Derived constructor called " << std::endl; }
Alone alone {};
void print() { Base::print(); };
};
int main()
{
Derived d;
d.print();
}
original link http://coliru.stacked-crooked.com/a/79f8ba2d9c38b965
I have a basic question first
How does memory allocation happen when using inheritance? I know the constructors are called from Base to Derived, but it seems that when I do
Derived d;
memory equivalent to sizeof(D) is allocated, and then constructors are called. Is my understanding correct here? (This would explain printing uninitialised member)
Considering the above example in mind, would you suggest/recommend any best practices when it comes to CRTP?
memory equivalent to sizeof(D) is allocated, and then constructors are called
How else could it possibly work? You can't construct an object in memory that isn't allocated yet. Memory allocation always comes before object construction.
Considering the above example in mind, would you suggest/recommend any best practices when it comes to CRTP?
The standard practices for the CRTP: don't call into the CRTP in a constructor/destructor. This is also true of virtual functions. Virtuals are dynamic polymorphism, while CRTP is static polymorphism. But they're both using the same basic mechanism: a base class that defines an interface that the derived class must implement.
And just like with virtual functions, trying to call it in constructors/destructors won't do what you mean. The only difference is that with virtual functions, the compiler will actually keep you from getting undefined behavior. Whereas with the CRTP, you just get breakage.
Note that this includes default member initializers, which for the purpose of non-aggregates are just shorthand for constructor initialization lists.

Non virtual version of virtual class

Lets say we have the following two class definitions.
#include <iostream>
#include <array>
class A
{
public:
virtual void f() = 0;
};
class B : public A
{
public:
virtual void f() { std::cout << i << std::endl; }
int i;
};
Here sizeof(B) == 8, presumably 4 the virtual pointer and 4 for the int.
Now lets say we make an array of B, like so:
std::array<B, 10> x;
Now we get sizeof(x) == 80.
If my understanding is correct, all method calls on elements of x are resolved statically, as we know the type at compile time. Unless we do something like A* p = &x[i] I don't see a need to even store the virtual pointer.
Is there a way to create an object of type B without a virtual pointer if you know it is not going to be used?
i.e. a template type nonvirtual<T> which does not contain a virtual pointer, and cannot be pointed to by a subtype of T?
Is there a way to create an object of type B without a virtual pointer if you know it is not going to be used?
No. Objects are what they are. A virtual object is virtual, always.
After all, you could do this:
A *a = &x[2];
a->f();
That is perfectly legitimate and legal code. And C++ has to allow it. The type B is virtual, and it has a certain size. You can't make a type be a different type based on where it is used.
Answering my own question here, but I've found that the following does the job, by splitting A into it's virtual and non-virtual components:
enum is_virtual
{
VIRTUAL,
STATIC
};
template <is_virtual X>
class A;
template<>
class A<STATIC>
{
};
template<>
class A<VIRTUAL> : public A<STATIC>
{
public:
virtual void f() = 0;
virtual ~A() {}
};
template <is_virtual X>
class B : public A<X>
{
public:
void f() { std::cout << i << std::endl; }
int i;
};
The important thing here is that in B<> don't specify f() as virtual. That way it will be virtual if the class inherits A<VIRTUAL>, but not virtual if it inherits A<STATIC>. Then we can do the following:
int main()
{
std::cout << sizeof(B<STATIC>) << std::endl; // 4
std::cout << sizeof(B<VIRTUAL>) << std::endl; // 8
std::array<B<STATIC>, 10> x1;
std::array<B<VIRTUAL>, 10> x2;
std::cout << sizeof(x1) << std::endl; // 40
std::cout << sizeof(x2) << std::endl; // 80
}
That would be a nice one to have, but I can't think of any way to revoke virtual members or avoid storing the virtual pointer.
You could probably do some nasty hacks by keeping a buffer that's the size of B without the virtual pointer, and play with casts and such. But is all undefined behavior, and platform dependant.
Unfortunately it won't work in any normal sense as the code inside the method calls expects the virtual pointer to be in the class definition.
I suppose you could copy/paste all of A and B's code into a new class but that gets to be a maintenance headache fast.

Multiple Inheritance from same grandparent - merge implementations?

for a certain project I have declared an interface (a class with only pure virtual functions) and want to offer users some implementations of this interface.
I want users to have great flexibility, so I offer partial implementations of this interface. In every implementation there is some functionality included, other functions are not overridden since they take care about different parts.
However, I also want to present users with a fully usable implementation of the interface as well. So my first approach was to simply derive a class from both partial implementations. This did not work and exited with the error that some functions are still pure virtual in the derived class.
So my question is if there is any way to simply merge two partial implementations of the same interface. I found a workaround by explicitely stating which function I want to be called for each method, but I consider this pretty ugly and would be grateful for an mechanism taking care of this for me.
#include <iostream>
class A{
public:
virtual void foo() = 0;
virtual void bar() = 0;
};
class B: public A{
public:
void foo(){ std::cout << "Foo from B" << std::endl; }
};
class C: public A{
public:
void bar(){ std::cout << "Bar from C" << std::endl; }
};
// Does not work
class D: public B, public C {};
// Does work, but is ugly
class D: public B, public C {
public:
void foo(){ B::foo(); }
void bar(){ C::bar(); }
};
int main(int argc, char** argv){
D d;
d.foo();
d.bar();
}
Regards,
Alexander
The actual problem is about managing several visitors for a tree, letting each of them traverse the tree, make a decision for each of the nodes and then aggregate each visitor's decision and accumulate it into a definite decision.
A separation of both parts is sadly not possible without (I think) massive overhead, since I want to provide one implementation taking care of managing the visitors and one taking care of how to store the final decision.
Have you considered avoiding the diamond inheritance completely, providing several abstract classes each with optional implementations, allowing the user to mix and match default implementation and interface as needed?
In your case what's happening is that once you inherit to D, B::bar hasn't been implemented and C::foo hasn't been implemented. The intermediate classes B and C aren't able to see each others' implementations.
If you need the full interface in the grandparent, have you considered providing the implementation in a different way, possibly a policy with templates, and default classes that will be dispatched into to provide the default behavior?
If your top level interface has a logical division in functionality, you should split it into two separate interfaces. For example if you have both serialization and drawing functions in interface A, you should separate these into two interfaces, ISerialization and IDrawing.
You're free to then provide a default implementation of each of these interfaces. The user of your classes can inherit either your interface or your default implementation as needed.
There is also the possibility that you could use a "factory" class for the main interface type. In other words the primary interface class also contains some type of static function that generates an appropriate child class on-request from the user. For instance:
#include <cstdio>
class A
{
public:
enum class_t { CLASS_B, CLASS_C };
static A* make_a_class(class_t type);
virtual void foo() = 0;
virtual void bar() = 0;
};
class B: public A
{
private:
virtual void foo() { /* does nothing */ }
public:
virtual void bar() { printf("Called B::bar()\n"); }
};
class C: public A
{
private:
virtual void bar() { /* does nothing */ }
public:
virtual void foo() { printf("Called C::foo()\n"); }
};
A* A::make_a_class(class_t type)
{
switch(type)
{
case CLASS_B: return new B();
case CLASS_C: return new C();
default: return NULL;
}
}
int main()
{
B* Class_B_Obj = static_cast<B*>(A::make_a_class(A::CLASS_B));
C* Class_C_Obj = static_cast<C*>(A::make_a_class(A::CLASS_C));
//Class_B_Obj->foo(); //can't access since it's private
Class_B_Obj->bar();
Class_C_Obj->foo();
//Class_C_Obj->bar(); //can't access since it's private
return 0;
}
If class A for some reason needs to access some private members of class B or class C, just make class A a friend of the children classes (for instance, you could make the constructors of class B and class C private constructors so that only the static function in class A can generate them, and the user can't make one on their own without calling the static factory function in class A).
Hope this helps,
Jason
Since you mentioned that you mainly needed access to the functions rather than data-members, here is another method you could use rather than multiple inheritance using templates and template partial specialization:
#include <iostream>
using namespace std;
enum class_t { CLASS_A, CLASS_B, CLASS_C };
template<class_t class_type>
class base_type
{
public:
static void foo() {}
static void bar() {}
};
template<>
void base_type<CLASS_A>::foo() { cout << "Calling CLASS_A type foo()" << endl; }
template<>
void base_type<CLASS_B>::bar() { cout << "Calling CLASS_B type bar()" << endl; }
template<>
void base_type<CLASS_C>::foo() { base_type<CLASS_A>::foo(); }
template<>
void base_type<CLASS_C>::bar() { base_type<CLASS_B>::bar(); }
int main()
{
base_type<CLASS_A> Class_A;
Class_A.foo();
base_type<CLASS_B> Class_B;
Class_B.bar();
base_type<CLASS_C> Class_C;
Class_C.foo();
Class_C.bar();
return 0;
}
Now if you need non-static functions that have access to private data-members, this can get a bit trickier, but it should still be doable. It would though most likely require the need for a separate traits class you can use to access the proper types without running into "incomplete types" compiler errors.
Thanks,
Jason
I think the problem is that when using simple inheritance between B and A, and between C and A, you end up with two objects of type A in D (each of which will have a pure virtual function, causing a compile error because D is thus abstract and you try to create an instance of it).
Using virtual inheritance solves the problem since it ensure there is only one copy of A in D.