Diamond Problem
The diamond problem is where it may be ambiguous as to which parent class a particular feature is inherited from if more than one parent class implements said feature.
Resources
- https://www.makeuseof.com/what-is-diamond-problem-in-cpp/ (though seems to have some minor errors)
Remembering the name
It is called the “Diamond Problem” because the problem arises from a class hierarchy that is shaped like a diamond (see image below)!
From CS247
The Diamond Problem stems from a shared base class with Multiple Inheritance.
struct A {int a = 1;}
struct B: A{};
struct C: A{}; // Don't need to specify public - structs have public inheritance by default
struct D: B, C{};
D dobj;
dobj.a = 2; // Doesn't compile either
Because a D
is-a B
and a C
, it ends up having 2 a
fields - one from the B
portion of the object and one from the C
portion of the object.
Must instead disambiguate - which a
field are we talking about? The one from the B
portion or the one from the C
portion?
- So you can use scope rsolation
dObj.B::a = 1 // setting different a fields in the D object
dObj.C::a = 2;
What if we wanted to disable this (somewhat strange) behaviour, and have only copy a single A
in our hierarchy? Solution: Use Virtual Inheritance.
Fix to Diamond Problem
The fix to the diamond problem is to use Virtual Inheritance.