Multiple Inheritance

You can derive a class from more than one base class. Deriving a class from more than one direct base class is called multiple inheritance.

In the following example, classes A, B, and C are direct base classes for the derived class X:

class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };

The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.

A direct base class cannot appear in the base list of a derived class more than once:

class B1 { /* ... */ };                   // direct base class
class D : public B1, private B1 { /* ... */ }; // error

However, a derived class can inherit an indirect base class more than once, as shown in the following example:

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

In the above example, class D inherits the indirect base class L once through class B2 and once through class B3. However, this may lead to ambiguities because two objects of class L exist, and both are accessible through class D. You can avoid this ambiguity by referring to class L using a qualified class name, for example, B2::L or B3::L .

You can also avoid this ambiguity by using the base specifier virtual to declare a base class.



Inheritance Overview


Examples of Single and Multiple Inheritance


Virtual Base Classes
Multiple Access
Derivation
Initialization by Constructor