C++ Virtual Function

Virtual function is used to select the member function belonging to class at runtime.

  • The classes that have virtual function are called polymorphic classes.
  • keyword virtual is used to make function virtual and bound dynamically.
  • when a function is made virtual, it allows the program to decide at run time which function to call based on the type of object pointed by the pointer rather than type of pointer itself.It is called dynamic or late binding.

Syntax:

class class_name { 
   private: 
      //…. 
   public: 
      virtual return_type function_name(args…) { 
           //…. 
   } 
};

 

Need of Virtual Function

Lets look at the following program in which we want to display different animals which are derived from a class Animal.

#include<iostream>
using namespace std;
class Animal
{
public:
    void display()
    {
        cout<<"\nFrom Base class Animal";
    }
};
class Cow:public Animal
{
public:
    void display()
    {
        cout<<"\nFrom Derived class Cow.";
    }
};
class Dog:public Animal
{
    void display()
    {
        cout<<"\nFrom Derived class Dog.";
    }
};
int main()
{
    Animal *panm;
    Animal anm;
    Cow cw;
    Dog dg;
    panm=&anm;
    panm->display();
    panm=&cw;
    panm->display();
    panm=&dg;
    panm->display();
    return 0;
}

The output of the program is:

From Base class Animal. 
From Base class Animal. 
From Base class Animal.

This output is not as expected because we had wished to call display() from different classes. This is because, during the compilation, it always selects the base class function as it is a pointer to the base class objects. The compiler is unknown about the address, which is known at the runtime and choose the member function that matches the type of pointer.

The following figure represents the above case pictorially.

virtual function example

Now, in order to achieve the runtime polymorphism in C++, virtual function is used.

Runtime polymorphism allows postponement of the decision of selecting a particular function until runtime.

To get runtime polymorphism, a pointer to object of base class should point to the object of its derived class.

In order to get the output as required, make a funtion virtual in base class Animal as below:

class Animal
{
     public: virtual void display() { 
          cout<<"\nFrom Base class Animal";
     } 
};

The output of the program becomes,

From Base class Animal. 
From Derived class Cow. 
From Derived class Dog.

The following picture depicts the working of a virtual function.

virtual function

Constructor and Destructor in Inheritance
C++ Exception Handling