Pure virtual functions, also known as abstract functions, are virtual functions that are declared in a base class but have no implementation. They are specified by assigning the value 0 to the virtual function declaration.
When a class contains at least one pure virtual function, it becomes an abstract class. Abstract classes cannot be instantiated, but they can be used as base classes for other classes.
The purpose of pure virtual functions is to provide an interface that derived classes must implement. By defining a pure virtual function in a base class, you are essentially forcing any concrete derived class to provide its own implementation for that function.
Here's an example:
#include <iostream>
class Monster {
public:
virtual void attack() = 0;
};
class Dragon : public Monster {
public:
void attack() override {
std::cout << "Dragon breathes fire!\n"; }
};
class Orc : public Monster {
public:
void attack() override {
std::cout << "Orc swings a club!\n"; }
};
int main() {
Monster* monsters[2];
monsters[0] = new Dragon();
monsters[1] = new Orc();
for (int i = 0; i < 2; ++i) {
monsters[i]->attack();
}
delete monsters[0];
delete monsters[1];
}
Dragon breathes fire!
Orc swings a club!
In this example, the Monster
class is an abstract class because it contains a pure virtual function attack()
. The Dragon
and Orc
classes are concrete classes that inherit from Monster
and provide their own implementations for the attack()
 function.
By using pure virtual functions, you can define an interface that derived classes must adhere to. This allows for polymorphic behavior and ensures that derived classes implement the required functionality.
Note that if a derived class does not implement all the pure virtual functions it inherits, it will also become an abstract class.
Pure virtual functions are a powerful tool for designing class hierarchies and enforcing contracts between base and derived classes.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to write flexible and extensible C++ code using polymorphism, virtual functions, and dynamic casting