Inheritance and virtual functions
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
Is-a relationships
Inheritance lets one class build on another. A Circle is a Shape. A SavingsAccount is an Account. The derived class gets the members of the base class and may add or change behaviour. The part that makes it powerful is polymorphism: code written against the base class works with any derived class, including ones that did not exist when the code was written.
A first hierarchy
#include <iostream>
#include <memory>
#include <numbers>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // pure virtual
virtual std::string name() const { return "shape"; }
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_{r} {}
double area() const override { return std::numbers::pi * r_ * r_; }
std::string name() const override { return "circle"; }
private:
double r_;
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_{w}, h_{h} {}
double area() const override { return w_ * h_; }
std::string name() const override { return "rectangle"; }
private:
double w_, h_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
shapes.push_back(std::make_unique<Rect>(3.0, 4.0));
for (const auto& s : shapes) {
std::cout << s->name() << ": " << s->area() << "\n";
}
}
The output is "circle: 12.5664" and "rectangle: 12". The loop only knows about Shape, yet each call runs the right version. The compiler achieves this with a hidden table of function pointers (a vtable) inside each object. Calls through a base pointer look up the right function at run time.
The keywords
virtualmarks a function that derived classes may replace.= 0makes it pure virtual. A class with at least one pure virtual function is abstract: you cannot create an object of it, only of a derived class that implements everything. This is how C++ expresses an interface.overridetells the compiler you intend to replace a base function. If you misspell the name or get a parameter wrong, the compiler errors instead of silently creating a new unrelated function. Always write it.finalstops further overriding, or stops a class being inherited from.
The virtual destructor rule
Notice virtual ~Shape() = default;. If you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs. The derived part never gets cleaned up, which is undefined behaviour. The rule is simple: any class meant to be used polymorphically gets a virtual destructor. With std::unique_ptr<Shape> holding a Circle the problem would hit you exactly in that case.
Object slicing
Polymorphism only works through pointers or references. If you pass a derived object by value to a function taking the base type, the derived part is cut off.
void printName(Shape s); // by value: does not compile for abstract Shape
void printName(const Shape& s); // by reference: correct
// Even for a non-abstract base, copying a Circle into a Shape variable
// keeps only the Shape part, and virtual calls then run Shape's versions.
Slicing is the reason you see containers of std::unique_ptr<Base> instead of std::vector<Base>.
Calling base class code
A derived class can call its parent's version by qualifying the name. Base constructors run first, and you choose which one in the initialiser list.
class Employee {
public:
Employee(std::string name, double salary) : salary_{salary}, name_{std::move(name)} {}
virtual ~Employee() = default;
virtual double monthlyPay() const { return salary_ / 12.0; }
const std::string& name() const { return name_; }
protected:
double salary_;
private:
std::string name_;
};
class Manager : public Employee {
public:
Manager(std::string name, double salary, double bonus)
: Employee{std::move(name), salary}, bonus_{bonus} {}
double monthlyPay() const override { return Employee::monthlyPay() + bonus_ / 12.0; }
private:
double bonus_;
};
protected means "visible to derived classes but not to the outside". Use it sparingly. Protected data breaks encapsulation across the hierarchy, and I usually keep fields private and expose a protected function if needed.
Composition over inheritance
Inheritance is the tightest coupling C++ offers. Change the base class and every derived class is affected. A good test: ask "is a" or "has a". A Car has an Engine; it is not an engine. Make the engine a member variable. Use inheritance when you really need substitution, meaning a function should accept any kind of shape, and reach for a member object otherwise.
Also keep hierarchies shallow. Two levels is normal. Five levels is a design that nobody can hold in their head.
Never call virtual functions in constructors
While the base constructor runs, the object is only a base. A virtual call there goes to the base version, not the derived one, even if the derived class overrides it. The same applies in the destructor. This surprises almost everyone once.
The common mistake
Forgetting the virtual destructor, and forgetting override. A subtler one: a derived function that differs only by const, for example double area() in the derived class versus double area() const in the base. That does not override, it hides, and the base version is called through a base pointer. The override keyword turns that silent bug into a compile error.
Try it yourself
- Add a
Triangleclass to the shapes example and a function that returns the shape with the largest area from the vector. - Remove
virtualfrom the destructor ofShape, add a print statement to each destructor, and see which destructors run. - Design an
Animalinterface withsound(), then write aDogandCat, and a function that acceptsconst Animal&.
#include <iostream>
#include <memory>
#include <numbers>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // pure virtual
virtual std::string name() const { return "shape"; }
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_{r} {}
double area() const override { return std::numbers::pi * r_ * r_; }
std::string name() const override { return "circle"; }
private:
double r_;
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_{w}, h_{h} {}
double area() const override { return w_ * h_; }
std::string name() const override { return "rectangle"; }
private:
double w_, h_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
shapes.push_back(std::make_unique<Rect>(3.0, 4.0));
for (const auto& s : shapes) {
std::cout << s->name() << ": " << s->area() << "\n";
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account