C++ – How to define virtual functions?

C++ is a Object Oriented language. C++ uses virtual keyword in different places. One of the use of virtual keyword is to create virtual functions.

An important feature in Object Oriented programming is Polymorphism; which means multiple-behaviors. An object has multiple behaviors and it shows particular behavior depending on its context. C++ achieves this with the help of virtual keyword by defining virtual functions.

Let’s take a simple example.

  • Create a class Shape and add one public method Display. Display method, just displays the name of the class.
  • Derive a class Circle from Shape class and add a method Display to it.
  • Now, create an instance of Circle class and assign it to a variable of type Shape.
  • Call Display method through the object and observe the results.
#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; to define the function as virtual.

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

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

By adding virtual keyword to Display method, at run time 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.

**

Add a Comment

Your email address will not be published.