Wednesday, February 20, 2008

Diamond Ring formation is Not a problem But a solution

Many a times in C++ people ( mostly interviewers ) ask : What is Diamond Ring problem?
The reply should be : It is not a problem rather a solution.
Scenario : When there is a common base class inherited by a child from immediate base classes. It leads to ambiguity. For e.g., Consider this situiation
class B : public A {};
class C : public A {};
class D : public B, public C {} //this leads to two instances of A in D , one from B another from C

The diagram looks like :
A A
\ /
B C
\ /
D
This causes two instances of A to be in D. Which leads to ambiguity problem the moment you create an instance of D.

The way to resolve is A should be inherited to B and C virtually.
i.e
class B : virtual public A {}
class C : public virtual A {}
class D : public B, public C {}

When it is virtual inheritance, it differs from normal inheritance. Standard doesn't talk about how to implement it. But the behavior is when you create any child class' object in the hierarchy what is guaranteed is the A class' constructor gets called directly from the child class ( I will write another post as how to create final class in C++ using virtual inheritance ).
In case of virtual inheritance the diagram would look like (diamond ring). This solves the ambiguity problem by having reference to A in B and C and not the instance of A.

A
/ \
B C
\ /
D

Final wordings : Diamond ring is actually a solution and not a problem.