Multiple inheritance is used to solve various complex relational problems in C++. At the same time, it also brings one ambiguity with it known as the diamond problem.

What is Diamond Problem in C++?

Consider the following example:

4 inheritance are taking place in the above example:

  • Class B inherits Class A.
  • Class C inherits Class A.
  • Class D inherits Class B and Class C as well.

There is no syntactical error in the above program but still, if you try to compile then it will give the following compilation error:

line 35|error: request for member ‘name’ is ambiguous

This is because there are two instances of name() method, one inherited by class B and the other one inherited by class C. So, the compiler gets confused and is not able to decide which name() method to call?

This ambiguity arose because of the presence of multiple instances of ‘class A’.

This problem is usually known as the Diamond Problem can be easily solved using virtual inheritance.

Diamond Problem in C++

What is Virtual Inheritance in C++?

Virtual inheritance is a technique in C++ that ensures that only one copy or instance of base class’s member variables is inherited by grandchild derived class.

It means that there will be only one instance of class A i.e B::A and C::A are same, and the same would be inherited and called by D.

To create a virtual inheritance virtual keyword is used.

Now when you run the above program then it will run without any compiler warnings or errors because there is only one name() method inherited/shared with all the classes.


Virtual Inheritance in C++

Hope you understood the concept of virtual inheritance and how to solve the diamond problem in C++. If you have any doubt then comment below.

Leave a Reply

twenty − twelve =