Skip to content

Diamond Problem / Multiple Inheritance

Multiple Inheritance: A class can inherit from more than one parent class in C++.

cpp
class C : public A, public B {}; // C inherits both A and B

What Is the Diamond Problem?

When two classes inherit from the same base, and a third class inherits from both — creating a diamond shape:

      A
     / \
    B   C
     \ /
      D

D inherits from B and C, both of which inherit from A. D has TWO copies of A — causes ambiguity!

The Problem

cpp
class A { public: int x = 10; void show() { /* ... */ } };
class B : public A {};
class C : public A {};
class D : public B, public C {};

int main() {
    D obj;
    obj.show(); // ERROR — ambiguous! which A::show()?
    obj.x = 20; // ERROR — which x? B's or C's?
}

Memory Layout — Without Virtual

Object D (without virtual)
├── B
│    └── A (copy 1) → x = 10
└── C
     └── A (copy 2) → x = 10  ← two separate copies!

Solution 1 — Scope Resolution (Partial Fix)

cpp
obj.B::show(); // explicitly call B's version
obj.C::show(); // explicitly call C's version
// Still two copies of A exist — not clean

Solution 2 — Virtual Inheritance (Correct Fix)

cpp
class B : virtual public A {}; // virtual inheritance
class C : virtual public A {}; // virtual inheritance
class D : public B, public C {}; // only ONE copy of A now

int main() {
    D obj;
    obj.show(); // OK — only one A
    obj.x = 20; // OK
}

Memory Layout — With Virtual Inheritance

Object D (with virtual)
├── B
├── C
└── A (only ONE shared copy)
     └── x = 10

Constructor Call Order with Virtual Inheritance

// Output when D obj is created:
// A constructor  ← virtual base constructed FIRST
// B constructor
// C constructor
// D constructor

With virtual inheritance, A is always constructed first by D directly.

Without vs With Virtual Inheritance

Without VirtualWith Virtual
Copies of ATwo copiesOne shared copy
AmbiguityYesNo
MemoryMoreLess
ConstructorCalled twiceCalled once
AccessAmbiguousDirect

Key Points

PointDetail
CauseTwo parents inheriting same base
ProblemDuplicate copies, ambiguity
Fixvirtual keyword in intermediate classes
Virtual baseConstructed first, only once
Scope resolutionB::method() for explicit calls

One-liner: "The diamond problem occurs when a class inherits from two classes that share a common base, causing ambiguity — solved in C++ using virtual inheritance which ensures only one shared copy of the base class exists."