oops · high
The Diamond Problem & Virtual Inheritance
D inheriting B and C (both from A) yields two A subobjects and an ambiguous d.x; virtual inheritance makes A a single shared base.
🔑 Key line
Non-virtual diamond gives D two copies of A (ambiguous); virtual inheritance (B, C : virtual A) gives one shared A.
The code
struct A { int x;};struct B : A {}; // non-virtualstruct C : A {};struct D : B, C {}; // TWO A subobjects -> d.x ambiguous
// Fix: virtual inheritancestruct B : virtual A {};struct C : virtual A {};struct D : B, C {}; // ONE shared AWhat this lesson walks through
- 01The diamond
- 02Non-virtual: D gets TWO copies of A
- 03d.x is ambiguous
- 04Fix: make A a virtual base
- 05One shared A subobject
- 06The cost
- 07The rule
D derives from B and C, and both B and C derive from A. The inheritance graph forms a diamond with A at the top.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of The Diamond Problem & Virtual Inheritance and 100+ animated C++ interview lessons.