Skills101

AdvancedC++ Programming · Lesson 16 of 17 · Updated ·

Multiple Inheritance in C++ — The Diamond Problem and Virtual Inheritance

Java and C# allow a class to extend only one class. C++ allows a class to inherit from several base classes at once. This is called multiple inheritance. It is powerful, but it brings two problems — ambiguous names and the diamond problem — that exams and interviews love to ask about. The inheritance lesson mentioned them in two lines; this lesson explains them properly.

1. Inheriting from two classes

A photocopier is both a printer and a scanner. In C++ we can say exactly that, listing the base classes separated by commas:

#include <iostream>
using namespace std;

class Printer {
public:
    Printer()  { cout << "Printer ctor\n"; }
    ~Printer() { cout << "Printer dtor\n"; }
    void print() { cout << "printing\n"; }
};

class Scanner {
public:
    Scanner()  { cout << "Scanner ctor\n"; }
    ~Scanner() { cout << "Scanner dtor\n"; }
    void scan() { cout << "scanning\n"; }
};

class Copier : public Printer, public Scanner {
public:
    Copier()  { cout << "Copier ctor\n"; }
    ~Copier() { cout << "Copier dtor\n"; }
    void copy() { scan(); print(); }        // uses both bases
};

int main() {
    Copier c;
    c.copy();
    return 0;
}
Printer ctor
Scanner ctor
Copier ctor
scanning
printing
Copier dtor
Scanner dtor
Printer dtor

Constructor order: base classes are built first, in the order they are listed in the class header (Printer, Scanner) — not the order you write them in a constructor's initialiser list. Then the derived class's own constructor body runs. Destructors run in exactly the reverse order.

2. Name ambiguity and the scope operator

What if both bases have a function with the same name? Suppose Printer and Scanner both have status(). Then c.status() does not compile: the compiler reports that the call is ambiguous, because it cannot guess which one you mean. There are two fixes:

  1. Name the base explicitly with the scope operator: c.Printer::status().
  2. Better: write status() in the derived class and decide there what it should do.
#include <iostream>
#include <string>
using namespace std;

class Printer {
public:
    string status() { return "paper OK"; }
};

class Scanner {
public:
    string status() { return "lid closed"; }
};

class Copier : public Printer, public Scanner {
public:
    string status() {                       // hides both, removes the ambiguity
        return Printer::status() + ", " + Scanner::status();
    }
};

int main() {
    Copier c;
    cout << c.Scanner::status() << "\n";    // pick one base explicitly
    cout << c.status() << "\n";             // the Copier's own version
    return 0;
}
lid closed
paper OK, lid closed

3. The diamond problem

Now suppose both Printer and Scanner inherit from a common base Device, which holds a serial number. Copier inherits from both. Drawn as a picture, the classes form a diamond.

Without any special care, a Copier object contains two separate Device parts — one inside its Printer part and one inside its Scanner part. That means two serial numbers, and Device's constructor runs twice.

#include <iostream>
using namespace std;

class Device {
public:
    int serial = 0;
    Device() { cout << "Device ctor\n"; }
};

class Printer : public Device {};
class Scanner : public Device {};
class Copier : public Printer, public Scanner {};

int main() {
    Copier c;
    // c.serial = 5;           // error: ambiguous — which Device?
    c.Printer::serial = 111;
    c.Scanner::serial = 222;
    cout << c.Printer::serial << " " << c.Scanner::serial << "\n";
    return 0;
}
Device ctor
Device ctor
111 222

One copier with two different serial numbers makes no sense. This duplication, and the ambiguity it causes, is the diamond problem.

Left: without virtual inheritance a Copier object holds two Device parts, one under Printer and one under Scanner. Right: with virtual inheritance Printer and Scanner share a single Device part

4. The fix: virtual inheritance

Write virtual in front of the base class in the middle classes: class Printer : virtual public Device. A virtual base class is shared: however many paths lead to it, the final object contains exactly one copy.

There is one new rule. Since Printer and Scanner share the Device part, neither of them may build it. The most-derived class (the class of the actual object, here Copier) is responsible for constructing the virtual base, and it is constructed before all other bases.

#include <iostream>
using namespace std;

class Device {
public:
    int serial;
    Device(int s) : serial(s) { cout << "Device ctor, serial " << s << "\n"; }
};

class Printer : virtual public Device {
public:
    Printer() : Device(1) { cout << "Printer ctor\n"; }
};

class Scanner : virtual public Device {
public:
    Scanner() : Device(2) { cout << "Scanner ctor\n"; }
};

class Copier : public Printer, public Scanner {
public:
    Copier() : Device(500) { cout << "Copier ctor\n"; }   // Copier builds Device
};

int main() {
    Copier c;
    c.serial = c.serial + 1;          // no ambiguity: there is only one serial
    cout << c.serial << "\n";
    Printer p;                        // a Printer on its own builds its own Device
    return 0;
}
Device ctor, serial 500
Printer ctor
Scanner ctor
Copier ctor
501
Device ctor, serial 1
Printer ctor

Look at the first line: when a Copier is built, Printer's request Device(1) and Scanner's Device(2) are ignored; only Copier's Device(500) is used. When a Printer is built on its own, it is the most-derived class, so its Device(1) is used.

Construction order for a Copier with virtual inheritance: the shared Device base first, then Printer, then Scanner, then Copier's own body; destructors run in reverse

Virtual inheritance has a small cost: the object stores extra hidden information to find its shared base, and access to it is slightly slower. So use it only where a diamond really exists.

5. Using multiple inheritance safely: interfaces

Most problems of multiple inheritance come from inheriting data from several places. A safe and common style is to inherit data from at most one class, and add interfaces — classes with only pure virtual functions and no data. This is the same idea as Java's implements.

#include <iostream>
#include <string>
using namespace std;

class Drawable {                                  // interface
public:
    virtual void draw() const = 0;
    virtual ~Drawable() = default;
};

class Saveable {                                  // interface
public:
    virtual string save() const = 0;
    virtual ~Saveable() = default;
};

class Circle : public Drawable, public Saveable {
    double r;
public:
    Circle(double r) : r(r) {}
    void draw() const override { cout << "drawing circle of radius " << r << "\n"; }
    string save() const override { return "circle " + to_string((int)r); }
};

void render(const Drawable &d) { d.draw(); }
void store(const Saveable &s)  { cout << "saved: " << s.save() << "\n"; }

int main() {
    Circle c(3);
    render(c);          // a Circle can be used wherever a Drawable is expected
    store(c);           // ... and wherever a Saveable is expected
    return 0;
}
drawing circle of radius 3
saved: circle 3

Interfaces have no data, so there is nothing to duplicate and no diamond problem, even if two interfaces share a parent.

SituationProblemSolution
Two bases with the same member nameambiguous callBase::name or override in the derived class
Two bases share a base (diamond)two copies of the shared basevirtual inheritance in the middle classes
Several roles for one class—one data base class + interfaces

Common mistakes

  • Thinking base constructors run in initialiser-list order. They run in the order of the class header.
  • Putting virtual on the wrong level: it goes on the middle classes (Printer : virtual public Device), not on Copier.
  • Expecting the middle classes' arguments to a virtual base to be used. The most-derived class constructs it.
  • Forgetting that a virtual base with no default constructor must be initialised by every most-derived class.
  • Using multiple inheritance to share data from many classes when composition (a member object) would be simpler.

Quick recap

  • class C : public A, public B inherits from both A and B.
  • Bases are constructed in header order, then the derived class; destruction is the reverse.
  • Same name in two bases → ambiguity; fix with A::name or an override.
  • Diamond problem: a shared base appears twice. Fix with virtual inheritance, giving one shared copy.
  • The most-derived class constructs the virtual base, before any other base.
  • Prefer one data base class plus pure-virtual interfaces.

Practice what you learned

📝 Quiz: Multiple Inheritance and the Diamond Problem5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →