Once again we are into a completely new topic with terminology which will be new to you. If you are new to object oriented programming, you should follow along in this tutorial very carefully because every attempt has been made to define every detail of this new and somewhat intimidating topic.

One term which must be defined is polymorphism, a rather large word that simply means similar when used in the context of object oriented programming. Objects are polymorphic if they have some similarities but are still somewhat different. We will see how it is used in the context of object oriented programming as we proceed.

We have already studied operator overloading and function overloading in this tutorial, and they are a subtle form of polymorphism since in both cases, a single entity is used to refer to two or more things. The use of virtual functions can be a great aid in programming some kinds of projects as you will see in these two chapters.

What is a Virtual Function?

A Virtual function is a function which is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.

Declaration of a virtual function

class BaseClass{
	public:
		virtual void who(void)
		{
			cout <<  "Base\n";
		}
	};
	class Derived1 : public BaseClass
	{
		public:
			void who (void)
			{
				cout <<  "Derived Class 1 \n";
			}
	};

	class Derived2 : public BaseClass
	{
		public:
			void who (void)
			{
				cout <<  "Derived Class 2\n";
			}
	};

	int main(void)
	{
		BaseClass b;
		BaseClass *bp;
		Derived1 d1;
		Derived2 d2;

		bp = &b;
		bp ->who();	//Executes the base class who function

		bp = &d1;
		bp ->who();	//Executes the Derived1 class who function

		bp = &d2;
		bp ->who();	//Executes the Derived2 class who function
	}
		//Out put
		//Base
		//Derived Class 1
		//Derived Class 2

Here in this example who(); function is called on the basis of the object. So if the object is of the base class then who(); function called is defined in base class.