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

C++ is a Object Oriented language. C++ uses virtial keyword for different places. One of this is in creating virtual functions.

One of the Object Oriented feature is Polymorpishm which means multiple-behaviours. An object has multiple behaviours and it shows particular behaviour depending on its context. C++ achieves this with the help of virtual keyword by defining virtual functions.

Lets take a simple example.

  • Create a class Shape and add one public method Display. Display just displays the name of the class.
  • Derive a class Circle from Shape class and add a method Display.
  • Now create an instance of Circle class and assign it to a variable of type Shape.
  • Call Display method through the object.
#include <iostream>

using namespace std;

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

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

int main() 
{ 	
	Shape *pShape = new Circle(); 	
	if ( pShape ) 	
	{ 		
		pShape->Display();

		delete pShape;
	}

	return 0;
}

After running this, it will display “Shape” instead of “Circle”. Actually in main(), we have created Circle class’s instance; but assigned to Shape type variable. We expect the result “Circle”. But it calls Shape‘s Display method instead of Circle‘s Display method. This is the place we need virtual keyword.

Modify Shape class by adding virtual keyword infront of Display method; like below.

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

By adding virtual keyword to Display method, at runtime it will call the exact method irrespective of the type of the object through which we are calling the method. In this case, it calls, Circle‘s Display method instead of Shape‘s Display method; which is what we are expecting.

We will discuss about other places where C++ using virtual keyword, in our next article.

**

Leave a Reply