Virtual base classes

Virtual base classes are used in multiple inheritance to prevent the same members from being inherited multiple times by derived classes that inherit the same parent through multiple paths.

For example, consider the following class hierarchy:

class A 
{
public:
    virtual ~A()
    {
    }
    virtual void method()
    {
    } 
};

class B : public A
{
public:
    virtual ~B()
    {
    }
};

class C : public A
{
public:
    virtual ~C()
    {
    }
};

class D : public B, public C
{
public:
    virtual ~D()
    {
    }
};

This has the following shape, called the "Dreaded Diamond":
Class diagram showing the

The problem now is that class D has inherited method() twice, once by each of its parents. This means that if you try to make a call to method() like this:

    D d;
    d.method();

The code won’t compile because the compiler doesn’t know which of the two copies of method() that d has inherited should be called.

You can get around this by qualifying the call to method with one or other of the parent classes as follows:

   d.B::method();

This isn’t very convenient, however. What you want to do is to prevent D from inheriting method() twice, and you can do this by making A a virtual base class of A and C:

class B : virtual public A
{
};

class C : virtual public A
{
};

Notice that it’s at the level of the parent classes that you declare virtual inheritance, rather than at the level of the derived class.

Having made A a virtual base class, method() is only inherited once by class D, and so calls to method() from d are unambiguous.