Skip to content

Module 6 · Inheritance and Polymorphism — topic 2 of 5

Polymorphism

One interface, many forms. Compare compile-time polymorphism (overloading, templates) with run-time polymorphism (virtual functions through base references).

Beginner 14 min read·Lesson 23 of 40 in C++ Programming

Learning objectives

  • Distinguish static and dynamic polymorphism
  • Call derived behaviour through base references and pointers
  • Store polymorphic objects in containers safely

Definition

Polymorphism is the ability of a single interface to work with different types. C++ provides compile-time (static) polymorphism through overloading and templates, and run-time (dynamic) polymorphism through virtual functions called via base-class pointers or references.

Introduction

area(shape) should work for circles, squares and triangles. With polymorphism the calling code doesn't need an if-else chain over every shape type; each type supplies its own behaviour and the right one runs automatically.

Why it matters

Polymorphism makes programs open for extension: adding a new shape requires no change to code that processes shapes.

It is a core OOP exam topic and appears in every framework you will use.

Detailed explanation

Static polymorphism: the compiler picks the function — overloading (print(int) vs print(double)) and templates (max<T>). No run-time cost.

Dynamic polymorphism: a virtual function called through a Base& or Base* runs the most-derived override, decided at run time.

Only references and pointers dispatch dynamically. Copying a derived object into a base value slices it, losing the derived behaviour.

Containers of polymorphic objects store pointers, typically std::vector<std::unique_ptr<Base>>.

Syntax

C++
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) std::cout << s->area(); // dynamic dispatch
  • The base class must declare the function virtual.
  • Use unique_ptr to own polymorphic objects.
  • Give the base a virtual destructor.

Code examples

Static polymorphism

C++
#include <iostream>
#include <string>
template <typename T>
T twice(T x) { return x + x; }
int main() {
std::cout << twice(21) << ' ' << twice(1.25) << ' ' << twice(std::string("ab")) << '\n';
return 0;
}
Output
42 2.5 abab

Dynamic dispatch through a reference

C++
#include <iostream>
struct Animal { virtual ~Animal() = default; virtual const char* sound() const { return "..."; } };
struct Cat : Animal { const char* sound() const override { return "meow"; } };
struct Cow : Animal { const char* sound() const override { return "moo"; } };
void speak(const Animal& a) { std::cout << a.sound() << '\n'; }
int main() {
Cat c;
Cow w;
speak(c);
speak(w);
return 0;
}
Output
meow
moo

More examples

A shape collection and object slicing

C++
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const { return 0; }
virtual const char* name() const { return "shape"; }
};
class Rect : public Shape {
public:
Rect(double w, double h) : w_(w), h_(h) {}
double area() const override { return w_ * h_; }
const char* name() const override { return "rect"; }
private:
double w_, h_;
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
const char* name() const override { return "circle"; }
private:
double r_;
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Rect>(3, 4));
shapes.push_back(std::make_unique<Circle>(1));
double total = 0;
for (const auto& s : shapes) {
std::cout << s->name() << ' ' << s->area() << '\n';
total += s->area();
}
std::cout << "total " << total << '\n';
Rect r(2, 5);
Shape sliced = r; // copies only the Shape part
std::cout << sliced.name() << ' ' << sliced.area() << '\n';
return 0;
}
Output
rect 12
circle 3.14159
total 15.1416
shape 0

Step-by-step explanation

  • The vector owns objects of different derived types through unique_ptr<Shape>.
  • s->area() dispatches to Rect or Circle at run time.
  • Shape sliced = r; copies only the base part, so it behaves as a plain Shape.
  • Pass and store polymorphic objects by pointer or reference to avoid slicing.

Expected output

Running “A shape collection and object slicing” prints exactly:

TextOutput
rect 12
circle 3.14159
total 15.1416
shape 0

Practical applications

  • Renderers draw any object implementing a Drawable interface.
  • Payment systems process any PaymentMethod.
  • Plugin architectures load classes that implement a known interface.

Best practices

  • Use virtual functions for behaviour that varies by type.
  • Own polymorphic objects with smart pointers.
  • Prefer templates when the type is known at compile time and speed matters.

Common mistakes

Storing derived objects by value in a base container

Avoid

std::vector<Shape> v;
v.push_back(Rect(1, 2));

Prefer

std::vector<std::unique_ptr<Shape>> v;
v.push_back(std::make_unique<Rect>(1, 2));

By-value storage slices every object to a Shape.

Type-switching instead of polymorphism

Avoid

if (s.type == RECT) area = w*h; else if (s.type == CIRCLE) area = ...;

Prefer

area = s.area(); // each class implements area()

Every new type would require editing every switch.

Important notes

  • Dynamic dispatch costs one indirect call; it prevents some inlining.
  • dynamic_cast<Derived*>(base) checks the real type at run time and returns nullptr if it doesn't match.

Key takeaways

  • Static polymorphism: overloading/templates, resolved at compile time.
  • Dynamic polymorphism: virtual functions via pointers/references.
  • Copying into a base value slices the object.

Try it yourself

  1. 1
    Add a Triangle class to the shape example without modifying the loop in main.
  2. 2
    Write a function template largest that works for ints, doubles and strings.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerFunction overloading and templates are examples of…
  • ModerateWhat is printed?
Practise this topic