http://en.wikipedia.org/wiki/Diamond_problem
I know what it means, but what steps can I take to avoid it?
The solution to the diamond problem is to use the virtual keyword. We make the two parent classes (who inherit from the same grandparent class) into virtual classes in order to avoid two copies of the grandparent class in the child class.
The "diamond problem" (sometimes referred to as the "Deadly Diamond of Death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C.
Which type of inheritance results in the diamond problem? Explanation: In diamond problem, hierarchical inheritance is used first, where two different classes inherit the same class and then in turn a 4th class inherits the two classes which had inherited the first class.
Deadly diamond of death is a problem which occurs with the inheritance of classes. In object-oriented programming, inheritance enables new objects to take on the properties of existing objects.
A practical example:
class A {}; class B : public A {}; class C : public A {}; class D : public B, public C {};
Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable.
To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue:
class A {}; class B : virtual public A {}; class C : virtual public A {}; class D : public B, public C {};
virtual inheritance. That's what it's there for.
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