Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid the Diamond of Death when using multiple inheritance?

http://en.wikipedia.org/wiki/Diamond_problem

I know what it means, but what steps can I take to avoid it?

like image 756
ilitirit Avatar asked Sep 26 '08 01:09

ilitirit


People also ask

How can you overcome the diamond problem in inheritance?

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.

What is diamond problem in multiple inheritance?

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.

What type of inheritance may lead to the Diamond problems?

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.

Which of the following reasons Deadly Diamond of Death problem occurs?

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.


2 Answers

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 {}; 
like image 97
Mark Ingram Avatar answered Sep 23 '22 22:09

Mark Ingram


virtual inheritance. That's what it's there for.

like image 37
eduffy Avatar answered Sep 22 '22 22:09

eduffy