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

ilitirit picture ilitirit · Sep 26, 2008 · Viewed 39.1k times · Source

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

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

Answer

Mark Ingram picture Mark Ingram · Sep 26, 2008

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 {};