How to Create a Pure Virtual Function in C++?
Last Updated :
07 Feb, 2024
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++
#include <iostream>
using namespace std;
class AbstractBase {
public :
virtual void pureVirtualFunction() const = 0;
void nonPureVirtualFunction() const
{
cout << "This is a non-pure virtual function.\n" ;
}
};
class Derived : public AbstractBase {
public :
void pureVirtualFunction() const override
{
cout << "Derived class implementing the pure "
"virtual function.\n" ;
}
};
int main()
{
Derived derivedObj;
derivedObj.pureVirtualFunction();
derivedObj.nonPureVirtualFunction();
return 0;
}
|
Output
Derived class implementing the pure virtual function.
This is a non-pure virtual function.
Share your thoughts in the comments
Please Login to comment...