Reputation: 770
I have the following situation, pictured is the theoretical inheritance graph of my classes:
The idea is basically to
1) have two abstract base classes that can be implemented on different platforms (in my case two different operating systems)
2) allow BBase to be up-castable to ABase to be able to handle both equally at times (e.g. to hold instances of both types in one list).
3) implement certain common functionality in ABase and BBase.
Now, what would be the best way to represent this in C++? Even though it does support multiple inheritance, multi-level inheritence like this is not possible to my knowledge. The problem is that B inherits from A and BBase, which both in turn inherit from ABase. Simply translating this 1:1 (following code) in C++, a C++ compiler (GNU) will complain that ABase::foo() is not implemented in B.
class ABase
{
public:
virtual void foo() = 0;
void someImplementedMethod() {}
};
class BBase : public ABase
{
public:
virtual void bar() = 0;
void someOtherImplementedMethod() {}
};
class A : public ABase
{
public:
A() {}
void foo() {}
};
class B : public A, public BBase
{
public:
B() : A() {}
void bar() {}
};
int main()
{
B b;
return 0;
}
How would you change this inheritance model to make it compatible to C++?
EDIT: Inverted arrows in diagram and corrected "down-castable" to "up-castable".
Upvotes: 6
Views: 429
Reputation: 20191
You can directly use that type of hierarchy in C++ by using virtual inheritance:
class ABase{...};
class BBase : public virtual ABase {...};
class A : public virtual ABase {...};
class B : public A, public BBase {...};
Of course if you plan on having more levels, it might be a good idea to use virtual inheritance for B too, so you would get
class B : public virtual A, public virtual BBase {...};
Upvotes: 7