Search⌘ K
AI Features

Polymorphism

Explore polymorphism in C++ to understand dynamic binding, virtual functions, and the override keyword. Learn how to prevent object slicing and the importance of virtual destructors for safe resource management. This lesson helps you design extensible systems that adapt behavior based on object types at runtime.

In the previous lesson, we established "is-a" relationships, e.g., an Electron is a Particle. You might naturally expect that if we pass an Electron to a function designed for a Particle, the program would automatically know to use the Electron's specific behavior.

However, C++ defaults to high-performance, compile-time decisions. Unless we explicitly request flexibility, the compiler ignores the object’s specific type and considers only the type of the variable that holds it. To fix this, we need polymorphism: the ability to swap behavior at runtime based on the actual object, not just the pointer or reference type.

The limitations of static binding

Let's start with the problem. We want to simulate different subatomic particles. We create a base class Particle and a derived class Electron. We also write a helper function simulate that accepts any Particle. You might expect that passing an Electron to simulate would trigger the Electron's logic. Let's see what actually happens.

C++
#include <iostream>
#include <string>
class Particle {
public:
// Intended to be overridden, but currently a normal function
void move() const {
std::cout << "Particle moves in a straight line.\n";
}
};
class Electron : public Particle {
public:
void move() const {
std::cout << "Electron moves in a chaotic wave.\n";
}
};
class Proton : public Particle {
public:
void move() const {
std::cout << "Proton moves in a stable path.\n";
}
};
// This function accepts ANY Particle (including derived ones)
void simulate(const Particle& p) {
p.move(); // Static binding: calls Particle::move()
}
int main() {
Electron e;
Proton p;
std::cout << "Simulation Start:\n";
simulate(e); // Expect Electron behavior
simulate(p); // Expect Proton behavior
return 0;
}

Let’s break this down step by step:

  • Lines 7–9: Particle defines a default move behavior. ...