CKTIS / C++
Pure virtual function (= 0) in C++
Use `= 0` to declare a pure virtual member function and define an abstract interface. Calls through that interface can select different implementations based on the object's type.
Version: ISO C++23; implementation support may vary
Syntax
struct Strategy {
virtual int apply(int x) const = 0;
virtual ~Strategy() = default;
};A pure virtual function (= 0) is declared with a pure-specifier, as in virtual int apply(int x) const = 0;. The = 0 is neither an assignment nor a return value. An override can itself be pure: int apply(int x) const override = 0;.
A class is abstract if the final overrider of any virtual function in that class is still pure. You cannot create a standalone object of an abstract class, but a base pointer or reference can refer to a concrete derived object. Use override to catch mistakes: dropping const from Half::apply means it no longer overrides Strategy::apply.
A pure virtual function can have an out-of-class definition and still be pure. A qualified call such as strategy.Strategy::apply(12) bypasses virtual dispatch and requires that definition. From an abstract class's constructor or destructor, a direct or indirect virtual call to a pure virtual function on the object being constructed or destroyed has undefined behavior, even if the function has a definition.
The public destructor virtual ~Strategy() = default; is defaulted, not pure. It ensures the correct destruction sequence in the example, where std::unique_ptr<Strategy> deletes a single object through Strategy*. If the destructor were declared pure with = 0, it would still need an out-of-class definition when derived objects are created.
print takes a const Strategy& instead of constructing its own strategy. This is dependency injection: the virtual call to apply selects the implementation based on the object's actual type. A factory registry can choose among strategies compiled into the program; virtual dispatch itself does not load shared libraries.
Examples
#include <iostream>
#include <memory>
struct Strategy {
virtual int apply(int x) const = 0;
virtual ~Strategy() = default;
};
struct Half : Strategy {
int apply(int x) const override { return x / 2; }
};
struct Third : Strategy {
int apply(int x) const override { return x / 3; }
};
void print(const Strategy& strategy) {
std::cout << strategy.apply(12) << '\n';
}
int main() {
std::unique_ptr<Strategy> half = std::make_unique<Half>();
std::unique_ptr<Strategy> third = std::make_unique<Third>();
print(*half);
print(*third);
}
Result
6 4
`Half` divides `12` by `2`, and `Third` divides it by `3`. The same `print` function prints `6` and then `4`.
Related lessons
- C++ · Lesson 59 · Advanced · Version: 3