The Analogy: The Universal Remote
One button on the remote is labelled play. Press it while the television is selected and the television plays. Press it with the sound system selected and the sound system plays. The button does not contain a list of every device ever made — it sends "play" and the device decides what that means.
That is polymorphism. The caller says what it wants; the object decides how. In C++ the remote button is a call through a base-class reference or pointer, and the deciding is done at runtime by the object's real type. The payoff is that you can plug in a device the remote has never heard of, and the remote does not change.
Inheritance gave us the family tree. Polymorphism is what makes the tree useful.
Syntax or Core Structure
Three keywords do the work: virtual in the base, override in the derived class, and = 0 for a method with no base implementation.
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class Notification {
public:
virtual ~Notification() = default; // essential -- see below
virtual std::string channel() const = 0; // pure virtual: no body here
virtual bool send(const std::string& message) const = 0;
// A non-virtual method that CALLS the virtual ones.
void deliver(const std::string& message) const {
std::cout << "[" << channel() << "] ";
std::cout << (send(message) ? "sent" : "failed") << "\n";
}
};
class Email : public Notification {
std::string address;
public:
explicit Email(std::string to) : address(std::move(to)) {}
std::string channel() const override { return "email"; }
bool send(const std::string& message) const override {
return !address.empty() && !message.empty();
}
};
class Sms : public Notification {
std::string number;
public:
explicit Sms(std::string to) : number(std::move(to)) {}
std::string channel() const override { return "sms"; }
bool send(const std::string& message) const override {
return number.size() >= 10 && message.size() <= 160;
}
};
int main() {
// One container, several concrete types, all handled uniformly.
std::vector<std::unique_ptr<Notification>> channels;
channels.push_back(std::make_unique<Email>("ada@example.com"));
channels.push_back(std::make_unique<Sms>("07700900123"));
channels.push_back(std::make_unique<Sms>("123")); // too short
for (const auto& c : channels) {
c->deliver("Your parcel is out for delivery");
}
return 0;
}
Output: [email] sent, [sms] sent, [sms] failed. deliver was written once and knows nothing about Email or Sms. Add a PushNotification class tomorrow and not a line of deliver changes.
Technical Depth: How Dynamic Dispatch Works
Static versus dynamic binding
Without virtual, the compiler picks the function from the declared type of the expression. With virtual, it defers to the object's actual type at runtime.
struct Base {
void plain() const { std::cout << "Base::plain\n"; }
virtual void poly() const { std::cout << "Base::poly\n"; }
};
struct Derived : Base {
void plain() const { std::cout << "Derived::plain\n"; } // hides
void poly() const override { std::cout << "Derived::poly\n"; }
};
Derived d;
Base& ref = d;
ref.plain(); // Base::plain -- decided at compile time
ref.poly(); // Derived::poly -- decided at run time
The vtable
A class with any virtual function gets a hidden vtable: a small array of function pointers, one per virtual method. Each object gains one hidden pointer to its class's vtable.
struct NoVirtual { int x; }; // sizeof == 4
struct HasVirtual { int x; virtual ~HasVirtual() = default; }; // sizeof == 16
A virtual call is therefore two loads and an indirect jump: fetch the vtable pointer, fetch the slot, call it. That is a handful of cycles, and it usually blocks inlining — which matters in a tight numeric loop and is irrelevant almost everywhere else. Do not avoid virtual on performance grounds without measuring first.
The virtual destructor is not optional
This is the single most important rule in the lesson.
class Base { public: ~Base() { std::cout << "~Base\n"; } }; // NOT virtual
class Derived : public Base {
std::vector<int> big;
public: ~Derived() { std::cout << "~Derived\n"; }
};
Base* p = new Derived;
delete p; // prints ~Base only -- Derived's members LEAK
Deleting through a base pointer with a non-virtual destructor is undefined behaviour. If a class has any virtual function, or is ever deleted through a base pointer, its destructor must be virtual. Write virtual ~Base() = default; and move on.
override and final earn their keep
override is not decoration; it is a spell-checker for your intentions.
class Base { public: virtual void run(int n) const; };
class Derived : public Base {
public:
void run(double n) const override; // ERROR -- caught immediately
void run(int n) override; // ERROR -- missing const
};
Without override both of those would compile as brand-new methods that silently never get called. Always write it.
final closes a method or class to further overriding, documents that intent, and lets the compiler devirtualise.
Pure virtual and abstract classes
= 0 means "derived classes must supply this". A class with at least one pure virtual method is abstract: it cannot be instantiated, only referred to.
Notification n; // ERROR: abstract
Notification* p = new Email("a@b"); // fine
A pure virtual method may still have a body, which derived overrides can call explicitly as a shared default:
void Notification::logAttempt() const { /* shared default */ }
An abstract class with only pure virtual methods and no data is an interface — the cleanest thing to inherit from, and safe to inherit from several at once.
Never call virtual methods from a constructor or destructor
During the base constructor the derived part does not exist yet, so the vtable still points at the base:
class Base {
public:
Base() { describe(); } // calls Base::describe, always
virtual void describe() const { std::cout << "base\n"; }
};
class Derived : public Base {
public:
void describe() const override { std::cout << "derived\n"; }
};
Derived d; // prints "base", not "derived"
If the base is abstract and calls a pure virtual from its constructor, the program is undefined behaviour. Do the work in a separate init() the caller invokes, or pass the value in.
Casting down the hierarchy
dynamic_cast asks "is this object really a Derived?", returning nullptr on a pointer when it is not:
void inspect(Notification& n) {
if (auto* sms = dynamic_cast<Sms*>(&n)) {
std::cout << "an SMS channel\n";
}
}
It works only on polymorphic types and costs a runtime check. A chain of dynamic_casts is usually a sign that a virtual method is missing from the base.
The modern alternatives
| Technique | Dispatch | Cost | Use when |
|---|---|---|---|
| Virtual functions | Runtime | Vtable indirection | Types vary at runtime, open set |
| Templates | Compile time | None | Types known at compile time |
std::variant + std::visit | Compile time | None, no allocation | Closed, known set of types |
std::function | Runtime | Indirection, maybe allocation | A single behaviour, not a whole type |
Overloading is sometimes called "compile-time polymorphism" — one name, several functions, chosen from the argument types. That is a different mechanism from the runtime dispatch above.
Real World Example: A Payment Processor
An abstract interface, three concrete methods, and calling code that never mentions a concrete type.
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <iomanip>
struct PaymentResult {
bool approved;
double feeCharged;
std::string detail;
};
// Abstract interface: no data, all behaviour, virtual destructor.
class PaymentMethod {
public:
virtual ~PaymentMethod() = default;
virtual std::string name() const = 0;
virtual double feeFor(double amount) const = 0;
virtual bool authorise(double amount) const = 0;
// Template method pattern: the algorithm is fixed here, the steps vary.
PaymentResult charge(double amount) const {
if (amount <= 0.0) { return {false, 0.0, "invalid amount"}; }
if (!authorise(amount)) { return {false, 0.0, name() + " declined"}; }
const double fee = feeFor(amount);
return {true, fee, name() + " approved"};
}
};
class CardPayment : public PaymentMethod {
std::string last4;
double limit;
public:
CardPayment(std::string digits, double creditLimit)
: last4(std::move(digits)), limit(creditLimit) {}
std::string name() const override { return "card ****" + last4; }
double feeFor(double amount) const override { return amount * 0.014 + 0.20; }
bool authorise(double amount) const override { return amount <= limit; }
};
class BankTransfer : public PaymentMethod {
std::string sortCode;
public:
explicit BankTransfer(std::string code) : sortCode(std::move(code)) {}
std::string name() const override { return "transfer " + sortCode; }
double feeFor(double) const override { return 0.0; } // flat, free
bool authorise(double amount) const override { return amount <= 250000.0; }
};
class GiftVoucher : public PaymentMethod {
double balance;
public:
explicit GiftVoucher(double value) : balance(value) {}
std::string name() const override { return "voucher"; }
double feeFor(double) const override { return 0.0; }
bool authorise(double amount) const override { return amount <= balance; }
};
// Written once. Knows nothing about cards, transfers or vouchers.
void takePayment(const PaymentMethod& method, double amount) {
const PaymentResult r = method.charge(amount);
std::cout << std::fixed << std::setprecision(2)
<< r.detail << " | fee " << r.feeCharged << "\n";
}
double totalFees(const std::vector<std::unique_ptr<PaymentMethod>>& wallet,
double amount) {
double sum = 0.0;
for (const auto& m : wallet) {
if (m->authorise(amount)) { sum += m->feeFor(amount); }
}
return sum;
}
int main() {
std::vector<std::unique_ptr<PaymentMethod>> wallet;
wallet.push_back(std::make_unique<CardPayment>("4242", 500.0));
wallet.push_back(std::make_unique<BankTransfer>("04-00-04"));
wallet.push_back(std::make_unique<GiftVoucher>(25.0));
for (const auto& method : wallet) {
takePayment(*method, 120.0);
}
std::cout << "-- a 400 pound charge --\n";
for (const auto& method : wallet) {
takePayment(*method, 400.0); // the voucher declines
}
std::cout << "combined fees at 120: " << totalFees(wallet, 120.0) << "\n";
// Pick the cheapest method that can cover the amount -- pure interface work.
const PaymentMethod* best = nullptr;
for (const auto& m : wallet) {
if (!m->authorise(300.0)) { continue; }
if (!best || m->feeFor(300.0) < best->feeFor(300.0)) { best = m.get(); }
}
std::cout << "cheapest for 300: " << (best ? best->name() : "none") << "\n";
return 0;
}
The interface is the design. PaymentMethod holds no data at all — just three pure virtual questions and one concrete method — which is what makes it safe to inherit from and impossible to instantiate by accident. charge is deliberately not virtual: the sequence "reject nonsense, authorise, then compute the fee" is the same for every payment method, so it is written once in the base and calls down into the virtual steps. That is the template method pattern, and it means a new payment type cannot accidentally skip the amount check. The three overrides all carry override explicitly, which is what catches the easy mistakes — drop the const from feeFor in BankTransfer and the compiler objects immediately instead of silently creating a new unrelated method that never runs. virtual ~PaymentMethod() = default is mandatory here because the wallet holds std::unique_ptr<PaymentMethod>, so each element is destroyed through a base pointer; without it, CardPayment::last4 would leak on every destruction. takePayment and totalFees take const PaymentMethod& and const std::unique_ptr<...>& rather than concrete types, so adding an ApplePay class tomorrow requires no edit to either — and note that passing by value would slice the object and lose the override entirely. The cheapest-method loop is the clearest demonstration of the payoff: it compares fees across three unrelated implementations using nothing but the interface, and best->feeFor(300.0) dispatches to a different body each time round.
Common Mistakes
- A non-virtual destructor on a polymorphic base. Deleting through a base pointer is undefined behaviour and leaks the derived members.
- Forgetting
virtualin the base and expecting a derived redefinition to be called. It hides instead, and the base version runs. - Omitting
override. A typo in the signature creates a silent new method rather than an error. - Passing polymorphic objects by value. Slicing removes the derived part and the virtual behaviour with it.
- Calling a virtual method from a constructor or destructor. The derived part does not exist yet, or no longer does.
- Storing objects by value in a
std::vector<Base>. Every element is sliced. Usestd::vector<std::unique_ptr<Base>>. - A chain of
dynamic_casts in the calling code. That is a virtual method the base is missing. - Adding data members to an interface, which makes multiple inheritance risky and couples every implementation to the layout.
- Trying to instantiate an abstract class. Only references and pointers to it are valid.
- Avoiding
virtualfor speed without measuring. The cost is a couple of indirections, not a redesign.
Best Practices
- Write
virtual ~Base() = default;in every class intended as a base. First line, every time. - Mark every override
override, and usefinalon leaves. - Prefer abstract interfaces with no data members, and keep them small — three or four methods.
- Hold polymorphic objects through
std::unique_ptr<Base>and pass them asconst Base&. - Put the fixed algorithm in a non-virtual base method and let virtual methods supply the varying steps.
- Never call a virtual method during construction or destruction.
- If you find yourself testing types, add a virtual method instead.
- Choose the mechanism deliberately: templates for compile-time variation,
std::variantfor a closed set, virtuals for an open one. - Keep the base's public interface stable; it is a contract every subclass and caller depends on.
Practice Exercises
- Shapes, properly: Write an abstract
Shapewith pure virtualarea()andname(), plusCircle,RectangleandTriangle. Store them in astd::vector<std::unique_ptr<Shape>>, print each one's name and area in a single loop, and add a fourth shape afterwards without touching the loop. - Prove the leak: Give a base and derived class printing destructors, delete a derived object through a base pointer with a non-virtual destructor, and record the output. Add
virtualand record it again. Then run both underg++ -fsanitize=addressand paste the difference. - override catches a typo: Take a working override and change its
const-ness, then its parameter type. Paste both compiler errors. Removeoverrideand show that the code now compiles but the method is never called. - Slice on purpose: Put
Circleobjects into astd::vector<Shape>(if the base allows it) or assign aCircleto aShapevariable, and observe whatarea()returns. Explain in a comment which part of the object went missing. - Replace the casts: Given a function containing three
dynamic_castbranches that each compute something different, refactor it into one virtual method on the base. Note how many lines the calling code lost.