Virtual Function in C++

  • Virtual function is a member function of class declared in base class and overrided in the derived class.
  • Derived class tells the compiler to perform late binding on this function.
  • Late binding is also called as Dynamic Binding or Runtime Binding. In this, function call is resolved at runtime, so compiler determines the type of object at runtime and then it binds the function call.
  • The virtual keyword is used to make a member function of the base class Virtual.

Example: Program demonstrating Virtual Function

#include<iostream>
using namespace std;
class BaseClass
{
    public:
         virtual void display()
         {
              cout << "Base class";
         }
};
class DerivedClass : public BaseClass
{
    public:
         void display()
         {
              cout << "Derived Class";
         }
};
int main()
{
     BaseClass *bc;       // Base class pointer
     DerivedClass dc;   // Derived class object
     bc = &dc;
     bc → display();     // Late Binding Occurs
}


Output:
Derived Class

In the above program, using virtual keyword with BaseClass class's function, late binding takes place and the derived version of function will be called, because base class pointer points to the derived class object.

Important points to be considered
  • If a function is declared as virtual in the base class, it will be virtual in all its derived classes.
  • The address of virtual function is placed in the virtual table and the compiler uses virtual pointer to point to the virtual function.
  • VTABLE is a Virtual Table contains the address of virtual functions of each class and VPTR is a Virtual Pointer, which points to the virtual function for that object.
  • Virtual function is declared with the keyword virtual in the base class and not in the definition.

Abstract Class and Pure Virtual Function

  • Abstract class is a class which defines an abstract type and cannot be instantiated.
  • It is used to provide an interface for its sub classes.
  • Abstract class contains at least one Pure Virtual Function in it.
  • Pure virtual function is function which has the notation “= 0” in the declaration of that function.
  • Pure virtual function don't have implementation, we only declare it.
  • If a base class contains at least one virtual function then that class is known as Abstract class.
  • Syntax
    class class_name
    {
         public:
              virtual void display() = 0; //Pure Virtual Function
    };
  • If “= 0” expression is added to the virtual function then function becomes pure virtual function.
Note: Adding “= 0” to virtual function does not assign a value. It only indicates that the virtual function is a pure function.

Why are Pure Virtual Functions necessary?

  • Lets one take example of Class Shape. The class Shape has a function called draw(). The other classes like Circle, Square and Triangle are derive from Shape class.
  • In the class Shape, it does not make any sense to provide a definition for the draw() function, because of one simple reason class Shape has no specific pattern or design. It is simply meant to act as a base class.
  • In the Circle, Square and Triangle classes we can define a draw() function with proper function definition because they should just draw either Circle or Square (respectively) on the page. But in the Shape class, it makes no sense to provide a function definition for the draw() function. And therefore a draw() function in the Shape class should be a Pure Virtual Function.

Characteristics of Abstract Class

  • Abstract class is mainly used for Upcasting, so that its derived classes can use its interface.
  • It cannot be instantiated, but pointers and references of Abstract class type can be created.
  • It can have normal functions and variables along with a Pure virtual function.

Example: Program demonstrating Abstract Class and Pure Virtual Function

#include <iostream>
using namespace std;
class Shape                    // Abstract class
{
    protected:
       float length;
    public:
       void get_input()          //Note: This function is not virtual.
       {
           length=5;
       }
       virtual float area() = 0; // Pure virtual function
};
class Square : public Shape
{
    public:
       float area()
       {   
            return length*length;  
       }
};
class Circle : public Shape
{
    public:
       float area()
       {
             return 3.14*length*length;
       }
};
int main()
{
    Square s;
    Circle c;
    s.get_input();
    cout<<"Area of Square: "<<s.area()<<endl;
    c.get_input();
    cout<<"Area of Circle: "<<c.area()<<endl;
    return 0;
}


Output:
Area of Square: 25
Area of Circle: 78.5

In the above program, pure virtual function virtual float area = 0 is defined inside class Shape, so this class is an abstract class and you cannot create object of class Shape.

If we create object for abstract class, it will display error, because when we create a pure virtual function in Abstract class, we reserve a slot for a function in the Virtual Table (VTABLE) and it does not put any address in that slot. So the Virtual Table will be incomplete and because of that the compiler will not let the creation of object for such class and will display an error message.