Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Diamond Problem in Inheritance

$
0
0

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.

The post Diamond Problem in Inheritance appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles