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

class A {
	void display()
	{
		//some code
	}
}

class B : public A{
	void display()
	{
		//some code
	}
}

class C : public A{
	void display()
	{
		//some code
	}
}

class D : public B, public C{
	//contains two display() functions
}

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.

class A {
	void display()
	{
		//some code
	}
}

class B : virtual public A{
	void display()
	{
		//some code
	}
}

class C : virtual public A{
	void display()
	{
		//some code
	}
}

class D : public B, public C{
	//contains one display() functions
}

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.

1 thought on “Diamond Problem in Inheritance”

  1. In the above mentioned code, after virtually inheriting class A to both the classes B and C, it still doesn’t solves the problem.

    Referring to your above code, if I call –
    int main()
    {
    D d1;
    d1.display();
    /* It will still give compiler error, since display is overridden in both the classes B and C and it will still have 2 copies in class D (one from B and one from C) so here there will be ambiguity between class B::display() and C::display()*/
    }

    Please check and update accordingly, it seems quite misleading.

    Thanks
    Amit

Leave a Comment

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