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.
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?
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.