C++ abstract base class
An abstract base class is a class that cannot be used to create objects directly.
It is used as a common interface for derived classes.
In C++, a class becomes abstract when it has at least one pure virtual function.
The = 0 means:
derived classes must implement this function.
Simple example
Output:
Animal defines the interface.
Dog and Cat provide the real behavior.
You cannot create the base object
This is not allowed:
Why?
Because Animal::speak() has no implementation.
Only derived classes that implement all pure virtual functions can be created.
Practical use
Abstract base classes are useful when different classes should be used through the same interface.
Example: different file exporters.
save_report() does not care which exporter it receives.
It only needs something that follows the Exporter interface.
This lets you add another exporter later without changing save_report().
Key point
Use an abstract base class when you want to define what derived classes must do, without deciding how they do it.
Common rules:
- use pure virtual functions for required behavior
- use
overridein derived classes - use a virtual destructor in the base class