🏛️Go deeper — read the bookObject-Oriented Programming in C++— runnable code & full walkthrough →

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-virtual
struct C : A {};
struct D : B, C {}; // TWO A subobjects -> d.x ambiguous
// Fix: virtual inheritance
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {}; // ONE shared A

What this lesson walks through

  1. 01The diamond
  2. 02Non-virtual: D gets TWO copies of A
  3. 03d.x is ambiguous
  4. 04Fix: make A a virtual base
  5. 05One shared A subobject
  6. 06The cost
  7. 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.

← Previous
Access Specifiers & Inheritance Modes
Next →
C++: Name Mangling, extern C, Inheritance Access Rules, Virtual Destructor