Diamond Problem in Inheritance

Diamond problem occurs when we use multiple inheritance in programming languages like C++ or Java.

Let’s understand this with one example.

Diamond Problem in Inheritance

Suppose there are four classes A, B, C and D. Class B and C inherit class A. Now class B and C contains one copy of all the functions and data members of class A.

Class D is derived from Class B and C. Now class D contains two copies of all the functions and data members of class A. One copy comes from class B and another copy comes from class C.

Let’s say class A have a function with name display(). So class D have two display() functions as I have explained above. If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C. If you will compile above program then it will show error.

Diamond Problem in Inheritance

This kind of problem is called diamond problem as a diamond structure is formed (see the image).

How to Remove Diamond Problem in C++?

We can remove diamond problem by using virtual keyword. It can be done in following way.

You can see we have marked class B and C as virtual. Now compiler takes care that only one copy of data members and functions of class A comes to class D.

How to Remove Diamond Problem in Java?

To remove this problem java does not support multiple inheritance. Although we can achieve multiple inheritance using interfaces.

Comment below if you found anything missing or incorrect in above diamond problem tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.