Tutorials / C++: From Basics to Modern C++ / Inheritance and virtual functions

Inheritance and virtual functions

17 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. 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

  • virtual marks a function that derived classes may replace.
  • = 0 makes 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.
  • override tells 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.
  • final stops 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

  1. Add a Triangle class to the shapes example and a function that returns the shape with the largest area from the vector.
  2. Remove virtual from the destructor of Shape, add a print statement to each destructor, and see which destructors run.
  3. Design an Animal interface with sound(), then write a Dog and Cat, and a function that accepts const Animal&.
cpp
#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