Thuta Learning
C++
AdvancedProgrammingBeginner

Polymorphism

C++Lesson 2335 min

What you'll walk away with

  • Tell static type from dynamic type and predict which function a virtual call runs
  • Use override and final so the compiler catches signature mistakes
  • Explain why every polymorphic base class needs a virtual destructor
  • Design an abstract interface with pure virtual functions and avoid object slicing

Explain it simply

Explain it simply

Think about the power button on a remote. Press it at a Sony TV and the Sony TV turns on; press it at a Samsung and the Samsung turns on. There is one button (the interface), but what happens depends on the device (the object) receiving the press.

Polymorphism means "many forms". In C++, when a base class function is marked virtual, calling draw() through a Shape& or Shape* makes the program look at the object's real type while it runs and pick Circle's draw() or Square's draw(). The caller never needs to know how many kinds of shape exist.

Problem → Why → Solution

The problem: without virtual, the base version always runs

Circle replaces Shape's draw() with its own version. But render() takes a Shape&, so passing it a Circle prints "Drawing a shape" instead of "Drawing a circle". There is no error and no warning; the program silently calls the wrong function.

no_virtual.cpp
#include <iostream>

class Shape {
public:
    void draw() const { std::cout << "Drawing a shape\n"; }   // not virtual
};

class Circle : public Shape {
public:
    void draw() const { std::cout << "Drawing a circle\n"; }
};

void render(const Shape& s) {
    s.draw();          // decided at compile time: always Shape::draw
}

int main() {
    Circle c;
    render(c);         // prints "Drawing a shape"
}

Why does it pick Shape::draw?

A call to a non-virtual function is resolved at compile time, and all the compiler knows then is the static type of s, which is const Shape&. It cannot know which object render() will receive later. Making draw() virtual moves the decision to runtime, where it follows the object's real (dynamic) type.

Core concept: a virtual call follows the dynamic type

Every expression has two types. The static type is the one written in the code (const Shape& s); the dynamic type is the real type of the object s refers to while the program runs (Circle). Non-virtual functions are chosen by static type, virtual functions by dynamic type. This dynamic dispatch only happens through a reference or a pointer, because a plain value such as Shape s = circle; can only ever have the dynamic type Shape.

When a derived class replaces a virtual function, always write override. To override, the name, parameters and const must match the base exactly. Drop one const and you have declared a brand-new function instead, while the base version keeps running; with override, the compiler turns that mistake into an error. final closes the door: no further overriding of that function, or no further deriving from that class.

When polymorphic objects are deleted through a base pointer, the base class destructor must be virtual. In Shape* p = new Circle; delete p;, a non-virtual ~Shape() makes the behavior undefined, and Circle's destructor may never run. g++ -Wall warns about exactly this: "deleting object of polymorphic class type 'Shape' which has non-virtual destructor might cause undefined behavior". The rule is simple: every base class with virtual functions gets virtual ~Base() = default;.

text
How compilers typically implement virtual calls (vtables)
---------------------------------------------------------
shapes[0] -> Circle object         Circle's vtable
             +----------------+    +------------------------+
             | vptr ----------+--> | Circle::~Circle()      |
             | Shape part     |    | Circle::draw() const   |
             +----------------+    +------------------------+
shapes[1] -> Square object         Square's vtable
             +----------------+    +------------------------+
             | vptr ----------+--> | Square::~Square()      |
             | Shape part     |    | Square::draw() const   |
             +----------------+    +------------------------+
shape->draw(): read vptr, load the draw entry, call it.

The standard does not prescribe an implementation, but most compilers keep one table of virtual function pointers (a vtable) per class and put a hidden pointer to it (the vptr) inside every polymorphic object. A virtual call is therefore an indirect call through a pointer, and each object grows by the size of one pointer.

Mental model: through the reference to the real object
  1. Call through a Base& or Base*
  2. Is the function virtual?
  3. Look up the object's dynamic type
  4. Run that class's override

If the function is not virtual, or you hold the object by value, the static type's version runs.

General pattern

cpp
class Base {
public:
    virtual ~Base() = default;                  // safe delete through Base*
    virtual Result action() const = 0;          // pure virtual: must override
    virtual Result hook() const { return fallback; }  // may override
};
class Derived final : public Base {             // final: no further deriving
public:
    Result action() const override;             // checked by the compiler
};

void use(const Base& obj) { obj.action(); }     // runs Derived::action

Give the base a virtual destructor first. A pure virtual function (= 0) must be overridden by every concrete derived class, while a plain virtual function supplies default behavior that derived classes may replace. On the derived side always write override, and handle objects through base references or pointers.

Example: drawing different shapes with one loop

This example stores a Circle and a Square in one vector as std::unique_ptr<Shape> and calls draw() in a single loop. The loop only knows about Shape, yet each object runs its own version. Because the base has a virtual destructor, the unique_ptrs destroy the objects correctly.

polymorphism.cpp
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Shape {
  public:
    virtual ~Shape() = default;

    virtual void draw() const {
        cout << "Drawing a shape" << endl;
    }
};

class Circle : public Shape {
  public:
    void draw() const override {
        cout << "Drawing a circle" << endl;
    }
};

class Square : public Shape {
  public:
    void draw() const override {
        cout << "Drawing a square" << endl;
    }
};

int main() {
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Circle>());
    shapes.push_back(make_unique<Square>());

    for (const auto& shape : shapes) {
        shape->draw();
    }
    return 0;
}

Code breakdown

  1. Line 8virtual ~Shape() = default;

    unique_ptr<Shape> deletes through a Shape*, so this virtual destructor makes sure the Circle and Square destructors run.

  2. Line 10virtual void draw() const {

    virtual means draw() is chosen by dynamic type. It has a body, so it is the default for any derived class that does not override it.

  3. Line 17void draw() const override {

    Replaces Shape::draw() const. Leave out the const and override turns the mismatch into a compile error, so the bug is caught immediately.

  4. Line 30vector<unique_ptr<Shape>> shapes;

    The container holds pointers, not the objects themselves. A vector<Shape> would copy only the Shape part of each Circle, which is slicing.

  5. Line 35shape->draw();

    The static type is unique_ptr<Shape>, but the first pass runs Circle::draw() and the second Square::draw(), printing "Drawing a circle" and "Drawing a square".

You should see
Drawing a circle
Drawing a square

Pure virtual functions and abstract classes

When a base class has no sensible default behavior, make the function pure virtual with = 0. A class with at least one pure virtual function is abstract, and you cannot create objects of that type directly: Notifier n; fails with "cannot declare variable 'n' to be of abstract type 'Notifier'". An abstract class is a promise that every class implementing the interface provides these functions.

notifier.cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

class Notifier {
public:
    virtual ~Notifier() = default;
    virtual void send(const std::string& message) const = 0;   // pure virtual
};

class EmailNotifier : public Notifier {
public:
    explicit EmailNotifier(std::string address) : address_(std::move(address)) {}
    void send(const std::string& message) const override {
        std::cout << "email to " << address_ << ": " << message << '\n';
    }
private:
    std::string address_;
};

class SmsNotifier final : public Notifier {
public:
    explicit SmsNotifier(std::string phone) : phone_(std::move(phone)) {}
    void send(const std::string& message) const override {
        std::cout << "sms to " << phone_ << ": " << message << '\n';
    }
private:
    std::string phone_;
};

int main() {
    std::vector<std::unique_ptr<Notifier>> channels;
    channels.push_back(std::make_unique<EmailNotifier>("aye@example.com"));
    channels.push_back(std::make_unique<SmsNotifier>("09-123456"));
    for (const auto& channel : channels) channel->send("Your order has shipped");
}

The output is "email to aye@example.com: Your order has shipped" and "sms to 09-123456: Your order has shipped". Adding a new channel, say push notifications, means writing one more class derived from Notifier and putting it in the vector; the loop does not change. SmsNotifier is final, so deriving from it is a compile error.

Object slicing

Copying a derived object into a value of the base type copies only the base part and cuts off the rest; this is called slicing. The copy's dynamic type is now the base, so virtual functions run the base version. Pass and store polymorphic objects only by reference, pointer or smart pointer.

slicing.cpp
#include <iostream>

class Shape {
public:
    virtual ~Shape() = default;
    virtual void draw() const { std::cout << "Drawing a shape\n"; }
};

class Circle : public Shape {
public:
    void draw() const override { std::cout << "Drawing a circle\n"; }
};

void byValue(Shape s) { s.draw(); }              // copies only the Shape part
void byReference(const Shape& s) { s.draw(); }   // sees the whole Circle

int main() {
    Circle c;
    byValue(c);
    byReference(c);
}

byValue(c) prints "Drawing a shape" while byReference(c) prints "Drawing a circle". One & in the signature changes the behavior completely.

dynamic_cast, when you really need the derived type

Sometimes you need to check whether a base pointer really points at a Circle so you can use a member only Circle has. dynamic_cast<const Circle*>(p) checks at runtime and returns the pointer if it is a Circle, or nullptr if not. Casting a reference instead throws std::bad_cast on failure. dynamic_cast only works on polymorphic types, meaning types with at least one virtual function.

dynamic_cast.cpp
#include <iostream>
#include <memory>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

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

class Square : public Shape {
public:
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
    double side;
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(1.0));
    shapes.push_back(std::make_unique<Square>(2.0));
    for (const auto& s : shapes) {
        if (const auto* c = dynamic_cast<const Circle*>(s.get())) {
            std::cout << "circle with radius " << c->radius << '\n';
        } else {
            std::cout << "not a circle, area " << s->area() << '\n';
        }
    }
}

The output is "circle with radius 1" and "not a circle, area 4". A long if-else chain of dynamic_casts is a design smell, though: instead of testing for each type, it is usually better to move that behavior into the base as a virtual function.

In real projects

Where this shows up in real projects

Polymorphism appears wherever types differ but the action is the same: update() on every entity in a game, the paint or draw functions of GUI widgets (Qt's QWidget::paintEvent is virtual), payment providers, notification channels, and plugins loaded into an application. Code written against an abstract interface also lets tests plug in a test double, such as a FakeNotifier that never really sends email.

A virtual call is usually cheap, one indirect call, but it is harder for the compiler to inline, which can matter in very tight loops that run millions of times per second. There, compile-time polymorphism with templates (lesson 27) or std::variant with std::visit are common alternatives. In ordinary application code, virtual functions are a good default for clarity.

Common mistakes

Common mistakes

1. Forgetting the virtual destructor in the base

With Shape* p = new Circle; delete p; and a non-virtual ~Shape(), the behavior is undefined: Circle's destructor may not run, leaking whatever Circle owns. Whenever you add a virtual function to a base class, add virtual ~Shape() = default; at the same time.

2. A mismatched signature without override

If the base has virtual void draw() const and the derived class writes void draw() without const, that is a new function, and calls through Shape& keep running the base version. Write void draw() override and g++ catches it at once: "'void Circle::draw()' marked 'override', but does not override".

3. Storing polymorphic objects by value

push_back a Circle into a std::vector<Shape>, or pass it to a by-value parameter like void render(Shape s), and slicing throws away the derived behavior. Use std::vector<std::unique_ptr<Shape>> and const Shape& instead.

4. Calling a virtual function from a constructor

While Shape's constructor runs, the Circle part does not exist yet, so the object behaves as a plain Shape. Calling draw() there runs Shape::draw(), not Circle::draw() (and a pure virtual call is even worse). The same holds inside destructors. Make the call after construction finishes.

Best practices

Best practices

  • Give every polymorphic base class a public virtual destructor.
  • Write override on every overriding function, and do not repeat virtual in the derived class; override says enough.
  • Design interfaces as pure virtual functions without data, and hold ownership with std::unique_ptr.
  • Treat dynamic_cast as an exception and prefer a virtual function over a chain of type checks.

Mini challenge

Mini challenge: payment fees

Write an abstract Payment interface and three payment methods for an online shop, then compute every fee in a single loop. Keep amounts in integer cents.

  • Payment has a virtual destructor and pure virtual name() const and fee(int amountCents) const
  • CardPayment = 3%, CashOnDelivery = always 150, WalletPayment (final) = 1% but at least 50
  • Every overriding function is marked override
  • Loop over a std::vector<std::unique_ptr<Payment>> and print each fee and the total for an amount of 2000
payments.cpp
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Payment {
public:
    // TODO: virtual destructor
    // TODO: pure virtual std::string name() const
    // TODO: pure virtual int fee(int amountCents) const
};

// TODO: class CardPayment       - 3% of the amount
// TODO: class CashOnDelivery    - a flat 150
// TODO: class WalletPayment     - final, 1% but never less than 50

int printFees(const std::vector<std::unique_ptr<Payment>>& methods, int amountCents) {
    // TODO: print "<name> fee: <fee>" for each method and return the sum
}

int main() {
    // TODO: fill the vector, call printFees(methods, 2000), print the total
}

Expected: The program prints: card fee: 60 cash on delivery fee: 150 wallet fee: 50 total fees: 260

Show hint

Compute 3% with integer arithmetic as amountCents * 3 / 100. For the minimum, use std::max(amountCents / 100, 50). CashOnDelivery's fee() ignores the amount, so write int fee(int) const override with no parameter name to avoid an unused-parameter warning.

Show solution
payments.cpp
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class Payment {
public:
    virtual ~Payment() = default;
    virtual std::string name() const = 0;
    virtual int fee(int amountCents) const = 0;
};

class CardPayment : public Payment {
public:
    std::string name() const override { return "card"; }
    int fee(int amountCents) const override { return amountCents * 3 / 100; }
};

class CashOnDelivery : public Payment {
public:
    std::string name() const override { return "cash on delivery"; }
    int fee(int) const override { return 150; }
};

class WalletPayment final : public Payment {
public:
    std::string name() const override { return "wallet"; }
    int fee(int amountCents) const override { return std::max(amountCents / 100, 50); }
};

int printFees(const std::vector<std::unique_ptr<Payment>>& methods, int amountCents) {
    int total = 0;
    for (const auto& method : methods) {
        int fee = method->fee(amountCents);      // dispatches on the real type
        std::cout << method->name() << " fee: " << fee << '\n';
        total += fee;
    }
    return total;
}

int main() {
    std::vector<std::unique_ptr<Payment>> methods;
    methods.push_back(std::make_unique<CardPayment>());
    methods.push_back(std::make_unique<CashOnDelivery>());
    methods.push_back(std::make_unique<WalletPayment>());

    int total = printFees(methods, 2000);
    std::cout << "total fees: " << total << '\n';
}

Quick quiz 1 / 3

Shape::draw() is virtual and Circle overrides it. With void render(Shape s) { s.draw(); }, what does Circle c; render(c); print?

Quick quiz 2 / 3

The base declares virtual void draw() const; and Derived writes void draw() override;. What happens?

Quick quiz 3 / 3

Shape has a virtual draw() but a non-virtual destructor. What is true about Shape* p = new Square; delete p;?

What to remember

  • A virtual function called through a reference or pointer runs the override for the object's dynamic type.
  • Write override on every override; final blocks further overriding or deriving.
  • Every polymorphic base needs a virtual destructor, and a class with a pure virtual (= 0) function is abstract.
  • Copying by value slices, so hold polymorphic objects by reference or smart pointer and use dynamic_cast sparingly.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Polymorphism | Thuta Learning