What is a pure virtual function in C++?

In object-oriented programming (OOP), a function can have different implementations across classes that inherit from the same parent. Hence, it is not possible to implement every function in a parent class. To achieve this, abstract classes and virtual functions are used.

Pure virtual functions

In C++, pure virtual functions are the ones that do not provide an implementation and must be overridden in a derived class. Let's look at how these functions work in C++.

Syntax

The keyword virtual is used to specify a virtual function within a class. The following syntax is followed when creating a pure virtual function:

virtual void functionName() = 0;

Here, void is the return type of the function. It can also be int, string, float, etc., depending upon the requirements. The = 0 specifies that the function is pure virtual.

Abstract base classes

The classes that contain pure virtual functions become abstract classes. We cannot initialize objects of abstract classes; the compiler throws an error if we try doing so. For example, running the following code will show an error.

Code

#include <iostream>
using namespace std;
class abstractClass {
public:
virtual void sayHello() = 0;
};
int main() {
abstractClass anObject = abstractClass();
}

  

Abstract derived class

It is necessary to implement the pure virtual function in a derived class; otherwise, the derived class becomes abstract too. For example, in the following code example, trying to initialize an object of the Derived class will throw an error.

Code

#include <iostream>
using namespace std;
class Base {
public:
virtual void sayHello() = 0;
};
class Derived: Base {
public:
void diffHello() {
cout << "Hi! I work!" << endl;
}
};
int main() {
Derived anObject = Derived();
}

Implementing the function in a derived class

Hence, we must provide the implementation of the pure virtual function in a derived class. Once we do that, we can initialize its object and work with them. The following example provides a complete implementation of how a pure virtual function works in C++.

Code

#include <iostream>
using namespace std;
class Base {
public:
virtual void sayHello() = 0;
};
class Derived: Base {
public:
void sayHello() {
cout << "This is the derived class saying hello!" << endl;
}
};
int main() {
Derived anObject = Derived();
anObject.sayHello();
}

Explanation

  • Line 6: Here, we define the pure virtual function sayHello().

  • Lines 11 to 13: We provide the implementation of the function sayHello() in the Derived class.

  • Lines 17 and 18: We initialize an object of the Derived class and then run anObject.sayHello() to call the sayHello() method.

Note: If you want to learn more about abstract classes, click here.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved