Open In App

How to Create a Pure Virtual Function in C++?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, pure virtual functions are those functions that are not implemented in the base class. They are instead implemented in the derived classes if necessary. In this article, we will discuss how to create a pure virtual function in a class in C++.

How to Create a Pure Virtual Function in C++?

To declare a member function as a pure virtual function, we can use the following syntax:

virtual function_name (arguements) {} = 0;

Classes that contain at least one pure virtual function are called abstract classes. If we don’t implement the pure virtual function in the derived class, then the derived class also becomes the abstract class and we cannot instantiate it.

C++ Program to Implement a Pure Virtual Function

C++




// C++ Program to demonstrate how to create a pure virtual
// function
#include <iostream>
  
using namespace std;
  
// Abstract base class with a pure virtual function
class AbstractBase {
public:
    // Pure virtual function
    virtual void pureVirtualFunction() const = 0;
  
    // Non-pure virtual function with an implementation
    void nonPureVirtualFunction() const
    {
        cout << "This is a non-pure virtual function.\n";
    }
};
  
// Derived class implementing the pure virtual function
class Derived : public AbstractBase {
public:
    // Implement the pure virtual function
    void pureVirtualFunction() const override
    {
        cout << "Derived class implementing the pure "
                "virtual function.\n";
    }
};
  
int main()
{
    // AbstractBase base;  // Error: Cannot instantiate an
    // object of an abstract class
  
    // Create an object of the derived class
    Derived derivedObj;
  
    // Call the pure virtual function through the derived
    // class object
    derivedObj.pureVirtualFunction();
  
    // Call the non-pure virtual function with an
    // implementation
    derivedObj.nonPureVirtualFunction();
  
    return 0;
}


Output

Derived class implementing the pure virtual function.
This is a non-pure virtual function.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads