Appearance
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 BWhat 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
\ /
DD 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 cleanSolution 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 = 10Constructor Call Order with Virtual Inheritance
// Output when D obj is created:
// A constructor ← virtual base constructed FIRST
// B constructor
// C constructor
// D constructorWith virtual inheritance, A is always constructed first by D directly.
Without vs With Virtual Inheritance
| Without Virtual | With Virtual | |
|---|---|---|
| Copies of A | Two copies | One shared copy |
| Ambiguity | Yes | No |
| Memory | More | Less |
| Constructor | Called twice | Called once |
| Access | Ambiguous | Direct |
Key Points
| Point | Detail |
|---|---|
| Cause | Two parents inheriting same base |
| Problem | Duplicate copies, ambiguity |
| Fix | virtual keyword in intermediate classes |
| Virtual base | Constructed first, only once |
| Scope resolution | B::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."