virtual inheritance

Gal Goldman picture Gal Goldman · Jan 7, 2009 · Viewed 67.5k times · Source

What is the meaning of "virtual" inheritance?

I saw the following code, and didn't understand the meaning of the keyword virtual in the following context:

class A {};
class B : public virtual A;

Answer

ogee picture ogee · Jan 7, 2009

Virtual inheritance is used to solve the DDD problem (Dreadful Diamond on Derivation).

Look at the following example, where you have two classes that inherit from the same base class:

class Base
{

public:

 virtual void  Ambig();

};

class C : public Base
{

public:

//...

};

class D : public Base
{
public:

    //...

};

Now, you want to create a new class that inherits both from C and D classes (which both have inherited the Base::Ambig() function):

class Wrong : public C, public D
{

public:

...

};

While you define the "Wrong" class above, you actually created the DDD (Diamond Derivation problem), because you can't call:

Wrong wrong;
wrong.Ambig(); 

This is an ambiguous function because it's defined twice:

Wrong::C::Base::Ambig()

And:

Wrong::D::Base::Ambig()

In order to prevent this kind of problem, you should use the virtual inheritance, which will know to refer to the right Ambig() function.

So - define:

class C : public virtual Base

class D : public virtual Base

class Right : public C, public D