Inheritance and Virtual Functions: Polymorphism and the Slicing Trap
Learn base classes, virtual functions, override, abstract interfaces and virtual destructors, hold different instruments in one vector of unique_ptr, and see what object slicing does.
In this lesson you will
- Define a base class and derived classes
- Use virtual functions and override
- Hold mixed objects in one container
- Avoid object slicing
About 28 minutes
Three instruments, one loop
Elena adds a thermometer, a hygrometer and a barometer to her station. Each is read in a different way, but the logging code should not need to know which kind it is dealing with. This is polymorphism: code written against a general type works with any specific type, and the right behaviour is chosen when the program runs. In C++ it needs three ingredients: a base class with a virtual function, derived classes that override it, and access through a pointer or a reference, not through a copy.
A function declared virtual in the base class can be replaced in a derived class, and a call through a base pointer runs the replacement belonging to the real object. A function declared with = 0 is pure virtual, which makes the class abstract: it cannot be instantiated and serves as an interface. Writing override in the derived class asks the compiler to check that you really override something, and final forbids further overriding. If a class has virtual functions it also needs a virtual destructor, so that deleting a derived object through a base pointer runs the derived destructor too, and without it the behaviour is undefined. The trap is slicing: copying a derived object into a base object by value keeps only the base part, and the virtual behaviour is lost.
| Keyword | Meaning |
|---|---|
| virtual | The function can be overridden and is chosen at run time |
| = 0 | Pure virtual: derived classes must provide it |
| override | Checked override of a virtual function |
| final | No further overriding |
| virtual ~Base() | Needed to delete through a base pointer |
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Instrument {
public:
explicit Instrument(std::string name) : name_(std::move(name)) {}
virtual ~Instrument() { std::cout << " ~Instrument " << name_ << "\n"; }
virtual double read() const = 0;
virtual std::string unit() const { return "?"; }
virtual std::string describe() const { return name_ + " in " + unit(); }
protected:
std::string name_;
};
class Thermometer : public Instrument {
public:
explicit Thermometer(double c) : Instrument("thermometer"), c_(c) {}
~Thermometer() override { std::cout << " ~Thermometer\n"; }
double read() const override { return c_; }
std::string unit() const override { return "C"; }
private:
double c_;
};
class Hygrometer : public Instrument {
public:
explicit Hygrometer(double p) : Instrument("hygrometer"), p_(p) {}
double read() const override { return p_; }
std::string unit() const override { return "%"; }
private:
double p_;
};
class Barometer final : public Instrument {
public:
explicit Barometer(double h) : Instrument("barometer"), h_(h) {}
double read() const override { return h_; }
std::string describe() const override { return "barometer reading " + std::to_string(static_cast<int>(h_)) + " hPa"; }
private:
double h_;
};
struct Plain { int a = 1; virtual int who() const { return 1; } virtual ~Plain() = default; };
struct Fancy : Plain { double b = 2.0; int who() const override { return 2; } };
int main() {
std::vector<std::unique_ptr<Instrument>> all;
all.push_back(std::make_unique<Thermometer>(21.5));
all.push_back(std::make_unique<Hygrometer>(63.0));
all.push_back(std::make_unique<Barometer>(1013.0));
double sum = 0;
for (const auto& i : all) { std::cout << i->describe() << " = " << i->read() << "\n"; sum += i->read(); }
std::cout << "sum of all readings: " << sum << "\n";
std::cout << "destroying the vector:\n";
all.clear();
Fancy f;
Plain& ref = f;
Plain sliced = f;
std::cout << "through a reference: " << ref.who() << ", sliced copy: " << sliced.who() << ", sizeof Fancy " << sizeof(Fancy) << " vs Plain " << sizeof(Plain) << "\n";
}
thermometer in C = 21.5
hygrometer in % = 63
barometer reading 1013 hPa = 1013
sum of all readings: 1097.5
destroying the vector:
~Thermometer
~Instrument thermometer
~Instrument hygrometer
~Instrument barometer
through a reference: 2, sliced copy: 1, sizeof Fancy 24 vs Plain 16
One loop handled three different classes. Each call to describe and read ran the version of the real object: the thermometer used the unit C from its override, the hygrometer used %, and the barometer replaced describe altogether, so the three lines read “thermometer in C = 21.5”, “hygrometer in % = 63” and “barometer reading 1013 hPa = 1013”. The sum of the readings is 1097.5, because the loop treated them uniformly. The vector holds unique_ptr, so the objects live on the heap, are owned by the vector, and are destroyed when it is cleared.
The destruction lines show why the virtual destructor matters. Clearing the vector deleted each object through a base pointer, and the output shows the derived destructor first, “~Thermometer”, then the base destructor, for the thermometer, and the base destructors alone for the other two, which have no destructor of their own. Without the virtual keyword on ~Instrument, deleting through a base pointer would skip the derived part, which is undefined behaviour. The override keyword on ~Thermometer asks the compiler to confirm this.
The last two lines show slicing. Through the reference, who() ran the derived version and returned 2. When the object was copied into a variable of the base type, only the base part was copied, the derived part and its extra member b were cut off, and who() returned 1. The sizes tell the same story: Fancy is 24 bytes and Plain 16. So pass polymorphic objects by pointer or reference, never by value.
Check by hand: 21.5 + 63 + 1013 = 1097.5. Destruction runs from the most derived class to the base class, the reverse of construction, and the barometer is marked final, so nothing can derive from it.
Without it, deleting a derived object through a base pointer is undefined behaviour. A virtual destructor costs a small amount of space and prevents a nasty bug.
Writing override makes the compiler check the signature. A typo or a missing const then becomes an error instead of a function that silently does not override.
Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state.
Practice
Add an Anemometer class that reports wind speed, and a method on Instrument that returns a warning string. Try removing virtual from the destructor and run the program under AddressSanitizer to see what it reports. Replace the vector of unique_ptr with a vector of Instrument values and see that it does not compile.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a virtual function allow?
- Faster code
- Private access
- A smaller class
- The version of the real object to run
Dynamic dispatch.
What does = 0 make a function?
- Static
- Private
- Pure virtual
- Deleted
The class becomes abstract.
Why does a base class need a virtual destructor?
- To run faster
- To be abstract
- To delete derived objects safely through a base pointer
- To hide members
Otherwise behaviour is undefined.
What is object slicing?
- Deleting an object
- Copying a derived object into a base object by value
- Sorting objects
- A kind of loop
The derived part is lost.
What does override do?
- Changes the access
- Makes the compiler check that a virtual function is overridden
- Creates a new function
- Deletes a function
It catches typos.
Summary
- Virtual functions are chosen by the real type at run time.
- Abstract classes with pure virtual functions define interfaces.
- Base classes need virtual destructors.
- Never copy polymorphic objects by value: slicing loses the derived part.
Questions
When should I use inheritance?
When there is a true is-a relationship and you need run-time polymorphism. For code reuse alone, prefer composition, templates or free functions.
What does final on a class do?
It forbids deriving from it, which can also let the compiler optimise virtual calls.
What is the cost of a virtual call?
A small indirect call through a table of function pointers. It matters only in very hot loops.
