Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

Multiple and Virtual Inheritance

The diamond problem, virtual base classes and ambiguity.

advanced #multiple-inheritance#virtual-inheritance#diamond-problem#ambiguity

Explanation

C++ allows a class to inherit from several bases: class C : public A, public B. This works well for interface bases (pure abstract classes) but causes trouble with data.

Ambiguity: if both bases have a member x, c.x is ambiguous; write c.A::x.

The diamond problem: if B and C both derive from A, and D derives from B and C, then D contains two A subobjects. Declaring the inheritance virtual (class B : virtual public A) makes all paths share one A. The most-derived class (D) is then responsible for constructing the virtual base.

Example

#include <iostream>

class Device {
public:
    explicit Device(int id) : id_(id) { std::cout << "Device(" << id_ << ")\n"; }
    int id() const { return id_; }
private:
    int id_;
};

class Scanner : virtual public Device {          // virtual: shared Device
public:
    Scanner() : Device(0) {}
    void scan() { std::cout << "scan " << id() << "\n"; }
};

class Printer : virtual public Device {
public:
    Printer() : Device(0) {}
    void print() { std::cout << "print " << id() << "\n"; }
};

class Copier : public Scanner, public Printer {
public:
    Copier() : Device(7) {}                       // most-derived class builds the virtual base
    void copy() { scan(); print(); }
};

int main() {
    Copier c;                                     // "Device(7)" printed once
    c.copy();                                     // both use the same Device: id 7
    return 0;
}

Remove the virtual keywords and c.id() becomes ambiguous: there would be two Device subobjects.

Common pitfalls

  • Forgetting that the most-derived class must initialize the virtual base; the intermediate classes’ initializers are ignored.
  • Object layout and pointer conversions become more complex and slightly slower with virtual bases.
  • static_cast from a virtual base to a derived class is not allowed; use dynamic_cast.
  • Prefer one concrete base plus any number of pure interface bases (Java/C# style).
  • Name hiding and overload resolution across multiple bases can surprise; qualify names.

Legacy vs modern

Nothing changes fundamentally; override and final (C++11) help verify overrides across bases. Composition or templates often avoid the need altogether.

Exercises

1. How many Device subobjects does Copier have, with and without virtual?

One with virtual inheritance, two without.