Polymorphism

Polymorphism in C++

Learn polymorphism in C++ with clear code examples: virtual functions, override, abstract classes, templates, and the mistakes beginners make most often.

On this page
  1. Polymorphism in C++ in brief
  2. Runtime polymorphism with virtual functions
  3. Use override to catch mistakes
  4. Give base classes a virtual destructor
  5. Abstract classes and pure virtual functions
  6. Avoid slicing: pass pointers or references
  7. Templates: compile-time polymorphism
  8. Function overloading and implicit conversions
  9. Common mistakes
  10. Key takeaways

Polymorphism in C++ in brief

Polymorphism means “many forms.” In C++, it lets you write code against a general type, such as a base class or a template parameter, and have the correct behavior chosen for the object or type you actually use. The same call, such as speak(), can produce different results depending on what it is called on.

C++ supports two broad kinds:

  • Runtime polymorphism is decided while the program runs. Virtual functions are the main tool.
  • Compile-time polymorphism is decided by the compiler. Templates and function overloading are the main tools.

This guide covers both, with code you can compile yourself.

Runtime polymorphism with virtual functions

A base class marks a function as virtual, and derived classes replace it with their own version. When you call that function through a pointer or reference to the base class, C++ runs the version that matches the object’s real type.

#include <iostream>
#include <memory>
#include <vector>

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

    virtual void speak() const {
        std::cout << "...\n";
    }
};

class Dog : public Animal {
public:
    void speak() const override {
        std::cout << "Woof\n";
    }
};

class Cat : public Animal {
public:
    void speak() const override {
        std::cout << "Meow\n";
    }
};

int main() {
    std::vector<std::unique_ptr<Animal>> animals;
    animals.push_back(std::make_unique<Dog>());
    animals.push_back(std::make_unique<Cat>());

    for (const auto& animal : animals) {
        animal->speak();  // prints "Woof", then "Meow"
    }
}

The loop never names Dog or Cat. It only knows about Animal. If you later add a Bird class that overrides speak(), you add a Bird to the vector, and the loop does not change.

The virtual keyword is what makes this work. Without it, the compiler picks Animal::speak() based on the pointer’s type, so the base version runs for every animal.

Most compilers store a hidden pointer in each polymorphic object that leads to a table of function pointers, called a vtable. You don’t need to manage this yourself, but it explains why a virtual call usually costs a little more than an ordinary function call.

Use override to catch mistakes

The override keyword, added in C++11, asks the compiler to confirm that a function really overrides a virtual function in a base class. Without it, a small mistake can quietly create a new function instead of replacing the old one.

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

class Square : public Shape {
public:
    double area() override {  // does not compile: the base function is const
        return 4.0;
    }
};

If you remove override, this code compiles. Square then has a second area() function that is not an override, and calls through a Shape reference still run the base version. Putting override on every function you mean to override makes this kind of bug show up at compile time.

Give base classes a virtual destructor

If you plan to delete derived objects through a base pointer, the base class’s destructor should be virtual. Without it, deleting the object is undefined behavior, and the derived class’s cleanup often never runs.

#include <iostream>

class Base {
public:
    ~Base() { std::cout << "Base cleanup\n"; }  // not virtual
};

class Derived : public Base {
public:
    ~Derived() { std::cout << "Derived cleanup\n"; }
};

int main() {
    Base* object = new Derived();
    delete object;  // undefined behavior: "Derived cleanup" often does not print
}

A simple habit is to give any class with a virtual function a virtual destructor too.

Abstract classes and pure virtual functions

A pure virtual function ends its declaration with = 0. A class with at least one pure virtual function is abstract. You can’t create objects of an abstract class, but you can use it as a base class and as the type of a pointer or reference.

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

class Circle : public Shape {
public:
    explicit Circle(double radius) : radius_(radius) {}

    double area() const override {
        return 3.14159 * radius_ * radius_;
    }

private:
    double radius_;
};

// Shape shape;      // error: Shape is abstract
Circle circle(2.0);  // fine: Circle overrides area()

Abstract classes are a common way to define an interface, meaning a set of functions every derived class must provide. Readers often ask, “What does an abstract class do?” In short, it sets a contract and leaves the details to the derived classes.

Avoid slicing: pass pointers or references

Polymorphic behavior needs a pointer or reference to the base class. If you pass a derived object by value to a base parameter, only the base part is copied. The derived part is lost, which is called slicing.

Using the Animal and Dog classes from the first example:

void speakByValue(Animal animal) {   // copies only the Animal part
    animal.speak();
}

void speakByReference(const Animal& animal) {
    animal.speak();                  // uses the real type
}

int main() {
    Dog dog;
    speakByValue(dog);      // prints "..."
    speakByReference(dog);  // prints "Woof"
}

Use const Base& when you only need to read the object. Use a pointer or smart pointer when you need to manage its lifetime.

Templates: compile-time polymorphism

Templates let one piece of code work with many types. The compiler generates a separate version for each type you use, so the choice is made at compile time and there is no virtual call at runtime. The types don’t need a common base class. They only need the operations the template uses.

#include <iostream>

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

private:
    double radius_;
};

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

private:
    double side_;
};

template <typename T>
void printArea(const T& shape) {
    std::cout << shape.area() << '\n';
}

int main() {
    printArea(Circle(2.0));  // prints 12.5664
    printArea(Square(3.0));  // prints 9
}

Circle and Square are unrelated classes, yet printArea works with both. In C++20 and later, concepts can state the required operations directly in the template, which makes compiler error messages easier to read.

Function overloading and implicit conversions

Overloading gives several functions the same name but different parameter lists. The compiler picks the best match when the code is compiled.

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }

int main() {
    add(2, 3);      // calls the int version
    add(2.5, 1.5);  // calls the double version
}

Overloading is often counted as a form of polymorphism, although it works differently from virtual functions. A common question is “What is function overloading?” The short answer is that the function is chosen by the compiler, based on the arguments.

The same idea applies to operators. Readers often ask, “Does C++ allow operator overloading?” It does. For example, std::cout << 42 and std::cout << "text" call different overloads of operator<<.

The compiler also converts values implicitly when no overload matches exactly. If only the double version of a function exists, passing an int still works, because the value is converted to double. This conversion, called coercion, is another form of ad hoc polymorphism.

Common mistakes

  • Forgetting virtual in the base class. Calls through a base pointer or reference then run the base version.
  • Skipping the virtual destructor. Deleting a derived object through a base pointer is undefined behavior.
  • Calling virtual functions from a constructor or destructor. While a base class constructor runs, the object’s dynamic type is the base class, so the base version runs even if a derived class overrides the function.
  • Slicing by value. Pass polymorphic objects by pointer or reference instead.
  • Expecting a derived default argument to apply. Default arguments are taken from the type used at the call site. If Base declares virtual void f(int x = 1) and Derived overrides it with void f(int x = 2) override, calling f() through a Base reference uses x = 1.
  • Hiding base overloads. A derived function with the same name hides all the base functions with that name. Bring them back with using Base::name;.

Key takeaways

  • Polymorphism lets one interface work with many types or behaviors.
  • Mark base functions virtual and mark overriding functions with override.
  • Give polymorphic base classes a virtual destructor.
  • Pass polymorphic objects by pointer or reference, not by value.
  • Templates provide compile-time polymorphism without a shared base class.

Keep exploring

Guides from other topics

All topics →

C++ Header File Example

A complete C++ header file example: a .h file with declarations, a .cpp file with definitions, a main program, and how to compile and run them.

Header Files 3 min read

Class Constructors in C++

Learn C++ class constructors with compilable examples: default and parameterized forms, member initializer lists, explicit, and initialization order.

Constructors 6 min read