Codiqo

Learn C++ · lesson 43 of 61 · about 10 minutes

Virtual Functions

Gather allies: use virtual functions and override so code written for a base class calls the right derived version.

What you'll learn

  • Mark functions virtual
  • Override them with override
  • Call through base references and pointers

Allies join

Word spreads, and people offer to help the hero: a healer, an archer, a villager with a pitchfork. They all do something when the fight starts, but each does it differently. The adventure writes one base class, Ally, with a virtual std::string act() const that just cheers, and Healer and Archer override it. The party is a std::vector<std::unique_ptr<Ally>>, and one loop calls act() on every ally: C++ runs each one's own version.

Polymorphism

A virtual function can be replaced in derived classes. When you call it through a base reference or pointer, C++ runs the version for the object's real type. That's polymorphism.

  • Write override on the derived version so the compiler checks you got the signature right
  • A base class with virtual functions needs a virtual destructor
  • = 0 makes a function pure virtual: derived classes must provide it

One loop, many shapes

#include <iostream>
#include <memory>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
    virtual const char* name() const { return "shape"; }
};

class Square : public Shape {
public:
    explicit Square(double s) : s_(s) {}
    double area() const override { return s_ * s_; }
    const char* name() const override { return "square"; }

private:
    double s_;
};

class Circle : public Shape {
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return 3.14 * r_ * r_; }

private:
    double r_;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Square>(3));
    shapes.push_back(std::make_unique<Circle>(1));
    for (const auto& s : shapes) std::cout << s->name() << " " << s->area() << "\n";
}

Output

square 9
shape 3.14

Tip

Circle didn't override name(), so it uses Shape's version. area() is pure virtual, so every shape must provide its own.

Why pointers?

A vector of Ally would hold plain allies: putting a Healer into it copies only the Ally part and throws away the rest. Storing std::unique_ptr<Ally> keeps each object whole, whatever its real type, and calls through -> reach the right override. An ally that isn't a healer or an archer is just made as a plain Ally, and gets the base version.

Base version as the default

#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Ally {
public:
    virtual ~Ally() = default;
    virtual std::string act() const { return "cheers"; }
};

class Archer : public Ally {
public:
    std::string act() const override { return "shoots"; }
};

int main() {
    std::vector<std::unique_ptr<Ally>> party;
    party.push_back(std::make_unique<Ally>());
    party.push_back(std::make_unique<Archer>());
    for (const auto& a : party) std::cout << a->act() << "\n";
}

Output

cheers
shoots

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.