Pure virtual functions are necessary when you want to define an interface that must be implemented by derived classes.
This is especially useful in designing frameworks or libraries where you want to ensure that certain functions are always implemented in the derived classes, providing specific behaviors.
For instance, imagine you are creating a game with different types of characters, and each character type must have a unique attack method.
You can define a pure virtual function in a base class Character
to enforce this requirement:
#include <iostream>
#include <string>
// Base class with a pure virtual function
class Character {
public:
virtual void Attack() = 0;
};
class Warrior : public Character {
public:
void Attack() override {
std::cout << "Warrior attacks with a sword!\n";
}
};
class Mage : public Character {
public:
void Attack() override {
std::cout << "Mage casts a fireball!\n";
}
};
int main() {
Warrior warrior;
Mage mage;
warrior.Attack();
mage.Attack();
}
Warrior attacks with a sword!
Mage casts a fireball!
In this example:
Character
has a pure virtual function Attack()
. This means Character
is an abstract class, and you cannot instantiate it directly.Warrior
and Mage
are derived classes that must provide an implementation of the Attack()
function. Each class defines its unique attack behavior.Using pure virtual functions ensures that every derived class implements the Attack()
method, providing the required behavior.
This design is essential when you want to enforce a specific interface across different classes, ensuring they adhere to a common contract.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions