Abstract classes and pure virtual functions in C++ let you define an interface without providing an implementation. A pure virtual function is one that a derived class must implement, and a class that still has one is abstract and cannot be instantiated. That turns a base class into a contract, because the compiler guarantees that whatever you hold a pointer to can actually do what the interface promises.
The previous lesson in this module covered "How Do Virtual Functions Enable Dynamic Dispatch?", and the next lesson in this module is about "Why Do Base Classes Need a Virtual Destructor?".
A pure virtual function
Adding = 0 to a virtual function declares it pure virtual. The function has no implementation in the base class.
#include <iostream>
#include <string>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual const char* kind() const = 0;
};
class Square : public Shape {
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
const char* kind() const override { return "square"; }
private:
double side_;
};
class Circle : public Shape {
public:
explicit Circle(double radius) : radius_(radius) {}
double area() const override { return 3.14159 * radius_ * radius_; }
const char* kind() const override { return "circle"; }
private:
double radius_;
};
int main() {
Square square(3.0);
Circle circle(2.0);
std::cout << square.kind() << ": " << square.area() << '\n';
std::cout << circle.kind() << ": " << circle.area() << '\n';
return 0;
}The output shows the two concrete classes doing their own work.
square: 9
circle: 12.5664Neither derived class inherits the pure virtual function. Each one provides its own, and the compiler refuses to let a class that has not.
You cannot instantiate an abstract class
Trying to create an object of an abstract class is a compile error.
Shape shape; // error: cannot instantiate an abstract class
Shape* pointer = nullptr; // fine: a pointer to the abstract type is allowedAnd the distinction is important. A pointer or a reference to an abstract class is perfectly legal, because it names a type and not an object. What is forbidden is creating an actual object, because there would be no implementation to call. That is why you can write a function that takes a Shape& and handles any shape at all.
#include <iostream>
#include <string>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual std::string describe() const = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : width_(width), height_(height) {}
double area() const override { return width_ * height_; }
std::string describe() const override {
return "rectangle of area " + std::to_string(area());
}
private:
double width_;
double height_;
};
void print(const Shape& shape) {
std::cout << shape.describe() << '\n';
}
int main() {
Rectangle box(3.0, 4.0);
print(box);
return 0;
}The output shows the function working with any shape.
rectangle of area 12.000000Pure virtual functions can have a body
A pure virtual function is not required to have no implementation. It may have a body, and that body is available to the derived classes that call it explicitly.
#include <iostream>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
double scaled(double factor) const {
return area() * factor;
}
protected:
// A pure virtual with a body: derived classes may call it.
virtual const char* fallback() const = 0;
};
class Square : public Shape {
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
protected:
const char* fallback() const override { return "square"; }
private:
double side_;
};
int main() {
Square square(4.0);
std::cout << "scaled: " << square.scaled(2.5) << '\n';
return 0;
}The output shows the helper using the derived implementation.
scaled: 40And that pattern is useful when the base class wants to provide a shared implementation of a higher-level operation, while still requiring the derived class to supply the primitive.
Templates use the same idea
The standard library is full of interfaces that look abstract. std::sort does not know what it is sorting, and it requires the element type to supply the comparisons. The library uses templates, but the shape is the same as a pure virtual interface.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual const char* kind() const = 0;
};
class Square : public Shape {
public:
explicit Square(double side) : side_(side) {}
double area() const override { return side_ * side_; }
const char* kind() const override { return "square"; }
private:
double side_;
};
class Circle : public Shape {
public:
explicit Circle(double radius) : radius_(radius) {}
double area() const override { return 3.14159 * radius_ * radius_; }
const char* kind() const override { return "circle"; }
private:
double radius_;
};
int main() {
std::vector<Shape*> shapes = {new Square(2.0), new Circle(1.0)};
std::sort(shapes.begin(), shapes.end(),
[](const Shape* left, const Shape* right) {
return left->area() < right->area();
});
for (const Shape* shape : shapes) {
std::cout << shape->kind() << ": " << shape->area() << '\n';
}
for (Shape* shape : shapes) {
delete shape;
}
return 0;
}The output shows the shapes sorted by area through a generic algorithm.
circle: 3.14159
square: 4Designing an abstract interface
A few habits make an abstract base class effective.
- Give it a virtual destructor. Deleting a derived object through a base pointer is
undefined behaviourwithout one. - Keep the interface small. Every pure virtual function is a burden on every derived class.
- Provide the non-virtual helpers. A base class can implement a shared operation in terms of the pure virtual primitives, and that keeps the logic in one place.
- Document the contract. The pure virtual declaration is the natural place for a comment that says what the implementation has to do.
- Do not add pure virtual functions late. Adding one to a published base class breaks every derived class that exists.
Quick reference
- A pure virtual function is declared with
= 0and it has no default implementation. - A class with at least one pure virtual function is abstract, and it cannot be instantiated.
- Pointers and references to abstract classes are perfectly legal.
- A pure virtual function may have a body that the derived classes can call.
- An abstract base class with a virtual destructor is the safe way to own the derived objects polymorphically.
- Adding a pure virtual function to an existing base class breaks every derived class.
Try it yourself: design an abstract Shape with the pure virtual area and perimeter methods, and implement them in a Rectangle and a Triangle. Then write a free function that takes a const Shape& and reports whether the shape is "squarish", which you define as an area-to-perimeter ratio above a threshold. Finally, try to instantiate a Shape directly and read the compiler's explanation of why it is not allowed.