41. Pure virtual functions

By | September 24, 2021

A pure virtual function is a virtual function that has no definition within the class. Let’s understand the concept of pure virtual function through an example.

In the above pictorial representation, shape is the base class while rectangle, square and circle are the derived class. Since we are not providing any definition to the virtual function, so it will automatically be converted into a pure virtual function.

Characteristics of a pure virtual function

  • A pure virtual function is a “do nothing” function. Here “do nothing” means that it just provides the template, and derived class implements the function.
  • It can be considered as an empty function means that the pure virtual function does not have any definition relative to the base class.
  • Programmers need to redefine the pure virtual function in the derived class as it has no definition in the base class.
  • A class having pure virtual function cannot be used to create direct objects of its own. It means that the class is containing any pure virtual function then we cannot create the object of that class. This type of class is known as an abstract class.

Syntax

There are two ways of creating a virtual function:

virtual void display() = 0;  

or

virtual void display() {}  

Example

Let’s understand through an example.
#include <iostream>  
using namespace std;  
class Base  
{  
    public:  
    virtual void show() = 0;  
};  
class Derived :
 public Base  
{  
    public:  
    void show()  
    {  
        std::cout << “Derived class is derived from the base class.” << std::endl;  
    }  
};  
int main()  
{  
    Base *bptr;  
    //Base b;  
    Derived d;  
    bptr = &d;  
    bptr->show();  
    return 0;  
}  

Output:

Derived class is derived from the base class.

In the above example, the base class contains the pure virtual function. Therefore, the base class is an abstract base class. We cannot create the object of the base class.

Leave a Reply

Your email address will not be published. Required fields are marked *