C++ Polymorphism
Polymorphism ("many forms") means that one interface can have many implementations. You write code against a base class, and at runtime each object behaves according to its actual derived type. In C++ this is achieved with virtual functions.
The problem without virtual
When a method is not virtual, the compiler picks the version based on the declared type of the reference or pointer, not the real object:
#include <iostream>
using namespace std;
class Animal {
public:
void speak() const { cout << "...\n"; }
};
class Cat : public Animal {
public:
void speak() const { cout << "Meow\n"; }
};
void makeItSpeak(const Animal& a) {
a.speak();
}
int main() {
Cat tom;
tom.speak(); // Meow
makeItSpeak(tom); // ... — the Animal version!
}Meow
...
Virtual functions
Mark the method virtual in the base class, and override in derived classes. Now the call is resolved at runtime based on the object's real type — this is called dynamic dispatch:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Animal {
public:
virtual ~Animal() = default;
virtual void speak() const { cout << "...\n"; }
};
class Cat : public Animal {
public:
void speak() const override { cout << "Meow\n"; }
};
class Cow : public Animal {
public:
void speak() const override { cout << "Moo\n"; }
};
class Fish : public Animal {}; // keeps the base version
int main() {
vector<unique_ptr<Animal>> zoo;
zoo.push_back(make_unique<Cat>());
zoo.push_back(make_unique<Cow>());
zoo.push_back(make_unique<Fish>());
for (const auto& a : zoo) {
a->speak();
}
}Meow
Moo
...
The loop does not know or care which animals are in the zoo. Adding a Duck later requires no change to that loop — that is the real power of polymorphism.
Tip: Always write
overrideon overriding functions. If you misspell the name or get the signature slightly wrong, the compiler reports an error instead of silently creating a new, unrelated function.
Virtual destructors
If objects are deleted through a base-class pointer (as unique_ptr<Animal> does), the base class must have a virtual destructor. Otherwise only the base part is destroyed — undefined behaviour and often a leak:
#include <iostream>
#include <memory>
using namespace std;
class Base {
public:
virtual ~Base() { cout << "~Base\n"; }
};
class Derived : public Base {
public:
~Derived() override { cout << "~Derived (frees its resources)\n"; }
};
int main() {
unique_ptr<Base> p = make_unique<Derived>();
} // both destructors run thanks to virtual ~Base~Derived (frees its resources)
~Base
Abstract classes and pure virtual functions
Sometimes the base class has no sensible default implementation. Declare the function pure virtual with = 0. A class with at least one pure virtual function is abstract: you cannot create objects of it, only of derived classes that implement every pure function. Abstract classes act as interfaces:
#include <iostream>
#include <vector>
#include <memory>
#include <string>
using namespace std;
class PaymentMethod {
public:
virtual ~PaymentMethod() = default;
virtual string name() const = 0;
virtual double fee(double amount) const = 0;
void charge(double amount) const { // shared, non-virtual logic
cout << name() << ": " << amount << " + fee " << fee(amount)
<< " = " << amount + fee(amount) << "\n";
}
};
class CreditCard : public PaymentMethod {
public:
string name() const override { return "Credit card"; }
double fee(double amount) const override { return amount * 0.03; }
};
class BankTransfer : public PaymentMethod {
public:
string name() const override { return "Bank transfer"; }
double fee(double) const override { return 0.5; }
};
int main() {
// PaymentMethod p; // error: cannot instantiate an abstract class
vector<unique_ptr<PaymentMethod>> methods;
methods.push_back(make_unique<CreditCard>());
methods.push_back(make_unique<BankTransfer>());
for (const auto& m : methods) {
m->charge(200);
}
}Credit card: 200 + fee 6 = 206
Bank transfer: 200 + fee 0.5 = 200.5
charge is written once in the base class but calls the right name() and fee() for each object. This pattern is known as the template method.
Compile-time vs runtime polymorphism
| Runtime polymorphism | Compile-time polymorphism | |
|---|---|---|
| Mechanism | virtual functions |
function overloading, templates |
| Decided | while the program runs | when compiling |
| Cost | one indirect call through the vtable | none |
| Flexibility | new types can be added without recompiling users | all types known at compile time |
Test yourself
What keyword makes a member function dispatch on the object's actual type?
- static
- override
- virtual
- dynamic
What makes a class abstract?
- It has no data members
- It has at least one pure virtual function (
= 0) - It is declared with
abstract - It has a virtual destructor
Why should a polymorphic base class have a virtual destructor?
- To make it faster
- So deleting through a base pointer also runs the derived destructor
- So it cannot be copied
- It is required for all classes