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".
Inheritance is the mechanism in java by which one class is allowed to inherit the features of another class. Interface is the blueprint of the class. It specifies what a class must do and not how.
Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
An interface can inherit from one or more interfaces. But unlike a ref class or struct, an interface doesn't declare the inherited interface members. If interface B inherits from interface A, and ref class C inherits from B, C must implement both A and B. This is shown in the next example. C++ Copy.
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 {...};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With