Polymorphism
Polymorphism means the same call or the same algorithm works on more than one type. C++ has compile-time polymorphism (templates, overloads) and runtime polymorphism (virtual functions). They solve different problems and cost different things.
Detailed Explanation
You have a list of shapes and you want to draw all of them. If every shape is a different type with a different draw, a single loop cannot name them unless something unifies the call. That unification is polymorphism.
Runtime polymorphism is the OOP meaning. A pointer or reference to a base names a derived object. Virtual functions dispatch to the derived override. The set of types can grow without recompiling the loop: you add Triangle, link it, and the same vector<unique_ptr<Shape>> draws it. The cost is a vptr, an indirect call, and a heap allocation if you store the objects via pointers. The type is erased to the base at the call site.
Compile-time polymorphism is templates and overloading. std::sort works on any type with iterators and a comparator. std::vector<T> is a different type for each T. The compiler generates a specialised copy. There is no vptr and the comparator can be inlined. The set of types is closed at the instantiation: adding a new T recompiles the algorithm for that T. Errors appear as instantiation failures unless you used concepts.
C++ also has a third, smaller form: a function pointer or std::function callback. The callee is chosen at runtime, but there is no hierarchy. Lambdas stored in std::function are this kind of erasure.
Pick runtime polymorphism when:
- You have a collection of mixed types that share an operation (
draw,handle,serialise). - Plugins or later translation units will add types.
- The operation set is small and stable, and the type set is open.
Pick templates when:
- The algorithm is generic (
find,hash,serializeto a writer). - You want zero overhead and you know the type at the call site.
- You are writing a container or a numeric kernel.
A common design is both: a template implementation for speed, and a virtual wrapper at the boundary where types mix (type erasure, std::function, a Concept plus a Model vtable). std::function itself is that pattern.
Slicing is the classic runtime-polymorphism bug. void f(Shape s) takes a Shape by value. Passing a Circle copies only the Shape part. Virtual calls inside f hit Shape. Pass const Shape& or unique_ptr<Shape>.
dynamic_cast and typeid are runtime queries. Prefer a virtual function that each type implements over a switch on typeid. The virtual function stays in sync when you add a type; the switch does not.
Code Examples
#include <iostream>
#include <memory>
#include <vector>
struct Shape {
virtual ~Shape() = default;
virtual void draw() const = 0;
};
struct Circle : Shape {
void draw() const override { std::cout << "circle\n"; }
};
struct Square : Shape {
void draw() const override { std::cout << "square\n"; }
};
void drawAll(const std::vector<std::unique_ptr<Shape>>& scene) {
for (const auto& s : scene) s->draw(); // runtime polymorphism
}
int main() {
std::vector<std::unique_ptr<Shape>> scene;
scene.push_back(std::make_unique<Circle>());
scene.push_back(std::make_unique<Square>());
drawAll(scene);
// prints:
// circle
// square
}#include <iostream>
#include <string>
template <typename T>
void twice(const T& x) { // compile-time polymorphism
std::cout << x << x << '\n';
}
int main() {
twice(3); // prints: 33
twice(std::string{"na"}); // prints: nana
}Common Gotchas
Slicing
`Shape s = circle;` or a by-value parameter drops the derived part. Use references, pointers, or `unique_ptr<Shape>`.
A template error is not a virtual miss
if `T` has no `<<`, `twice` fails at instantiate time, not with a fallback. Constrain with a concept or document the requirement.
`final` helps the compiler devirtualise
if a class is `final`, a virtual call through that concrete type can become a direct call.
Mixing both without a plan
a template that also takes a virtual base can instantiate a copy per type *and* pay a virtual call. Pick one dispatch per boundary.