Polymorphism in one sentence
Polymorphism in C++ means you can call the same function on different kinds of objects, and each object responds in its own way.
An everyday comparison
Picture a drawing app with a “draw” button. Select a circle and press the button, and a circle appears. Select a line and press the same button, and a line appears. The button’s name and action stay the same. The app doesn’t need to know which shape is selected, because each shape knows how to draw itself.
That is the idea behind polymorphism.
A small C++ example
#include <iostream>
#include <memory>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const {
std::cout << "Some shape\n";
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle\n";
}
};
class Line : public Shape {
public:
void draw() const override {
std::cout << "Drawing a line\n";
}
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>());
shapes.push_back(std::make_unique<Line>());
for (const auto& shape : shapes) {
shape->draw(); // each shape draws itself
}
}
The output is:
Drawing a circle
Drawing a line
Why it helps
The loop doesn’t need to know what each shape is. If you add a Square class later, you write the new class and add one to the vector. The loop stays the same. This keeps code that uses shapes separate from the code that defines each shape.
What makes it work
Three parts work together:
- The
virtualkeyword in the base class marksdraw()as a function that derived classes can replace. - The
overridekeyword in each derived class tells the compiler that the function replaces the base version. - The loop calls
draw()through a pointer to the base class, so C++ chooses the version that matches each object.
The shapes are derived classes, so this depends on inheritance. If that part is new, read “What is inheritance in C++ in simple words?” first.
If you forget virtual, the loop calls the base version for every shape. This is one of the most common beginner mistakes with polymorphism.
Common confusions
Is this the same as overloading? Not quite. Overloading gives several functions the same name with different parameters, and the compiler picks one when the code is built. Some people count overloading as polymorphism too, but the polymorphism in this article is chosen by the object’s real type while the program runs. If you are unsure about overloading, start with “What is function overloading?”
Can a base pointer call any function? No. The base class must declare the function. The pointer can only call functions that the base class provides.
Is it slow? A virtual call usually costs a little more than an ordinary call. For many programs that difference is small, but it is worth knowing about when speed matters.