Virtual Base Classes

If you have an inheritance graph in which two or more derived classes have a common base class, you can use a virtual base class to ensure that the two classes share a single instance of the base class.

In the following example, an object of class D has two distinct objects of class L, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifiers in the base lists of classes B1 and B2 to indicate that only one class L, shared by class B1 and class B2, exists.

For example:

class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // valid

Using the keyword virtual in this example ensures that an object of class D inherits only one object of class L.

A derived class can have both virtual and nonvirtual base classes. For example:

class V { /* ... */ };
class B1 : virtual public V { /* ... */ };
class B2 : virtual public V { /* ... */ };
class B3 : public V { /* ... */ };
class D : public B1, public B2, public B3 { /* ... */
};

In the above example, class D has two objects of class V, one that is shared by classes B1 and B2 and one through class B3.



Inheritance Overview


Multiple Inheritance
Multiple Access
Derivation