Suppose I have the following classes:
class Base {
virtual void func() { cout << "func base" << endl; }
};
class A : virtual public Base {
public:
virtual void func() { cout << "func A" << endl; }
};
class B : virtual public Base {
public:
virtual void func() { cout << "func B" << endl; }
};
class C : public A, public B {
C(bool is_a);
public:
virtual void func() { // Call appropriate parent's func here }
};
My requirement is that the appropriate parent class' function func()
be called when I call C's func()
. This is what I mean by appropriate:
Base* ptr = new C(true /*is_a*/);
ptr->func(); // This should call A's func internally
How to achieve this? Is it even possible?
[edit]
This might be more of a design question. It is known that class C will have only one true parent (either A or B). And depending on which is the parent, I want that function to be called. Any alternative design suggestions are welcome.
I am deriving C from A and B because there is some common functionality which both A and B share and which can't be a part of base class.
This might be more of a design question. It is known that class C will have only one true parent (either A or B). And depending on which is the parent, I want that function to be called. Any alternative design suggestions are welcome.
class Base { };
class A : public Base { };
class B : public Base { };
class C
{
// common interface for all types of C
};
class C_A : public A, public C { };
class C_B : public B, public C { };
Now you can use C_A
, wherever a C
needs to behave as A
and C_B
analogously...
In above example, all virtual inheritances are removed, they are not needed as is. Depending on the use case, it might or might not be appropriate to let class C
itself inherit from Base. If so, let all of A
, B
and C
inherit virtually from Base. C_A
and C_B
, though, do not need to inherit virtually from their parents (there still will just be one Base
instance inherited due to the virtual inheritance of the base classes).