C++: Why virtual? (Part-3)

Another interesting feature of Object Oriented Programming is its inheritance. Inheritance inherits the behaviors or attributes from its parent or base classes. C++ uses virtual inheritance to overcome the inheritance ambiguity in multiple-inheritance.

Inheritance ambiguity will occur when derived class object is converted to its parents’ parent class; where its immediate parents’ have common base class.

Lets take this example:

// Sample.cpp
//
#include <iostream>

using namespace std;

class Shape
{
public:
	virtual void Display()
	{
		cout << "Shape" << endl;
	}
};

class Circle : public Shape
{
public:
	void Display()
	{
		cout << "Circle" << endl;
	}
};

class Rectangle : public Shape
{
public:
	void Display()
	{
		cout << "Rectangle" << endl;
	}
};

class CircleInsideRectangle : public Circle, public Rectangle
{
public:
	void Display()
	{
		cout << "CircleInsideRectangle" << endl; 	
	} 
}; 
//
//  
int main()
{ 	
	Shape *pObj = new CircleInsideRectangle();
 	if ( pObj != NULL )
 		pObj->Display();

	return 0;
}

Observe that the Shape is the base class. Circle and Rectangle classes are derived from Shape class. Another class CircleInsideRectangle is created and it is derived from both Circle and Rectangle classes.

We can create an instance of CircleInsideRectangle class and assign to its super class Shape. Theoretically its correct.

Lets compile the code:

cl Sample.cpp /EHsc

The compiler throws the below error message:

sample.cpp(45) : error C2594: 'initializing' : ambiguous conversions from 'CircleInsideRectangle *' to 'Shape *'

Because, CircleInsideRectangle class is derived from Circle and Rectangle classes; and these classes have common parent class Shape. When we cast CircleInsideRectangle to Shape; it didn’t understand whether to cast to Circle’s Shape or Rectangle’s Shape.

One solution to this is, explicitly cast the objects. So, it will be like this:

Shape *pObj = (Circle *)new CircleInsideRectangle();

But, if we have large lines of code and if we need to do this type of casting in multiple places; this is not the recommended way. Other alternative is, use virtual inheritance.

If multiple classes have same base class, derive the classes using virtual inheritance instead of normal inheritance. So, at the time of assigning derived class object to its super class object; it will ensures to take single path to its super class.

So, our code will become like this:

class Circle : public virtual Shape

and

class Rectangle : public virtual Shape

Once you made these changes and compile the program; it will compile with NO errors.

These are the benefits to use virtual keyword in C++ programming language.

..

Leave a Reply