Polymorphism is an OOP concept that lets the same interface/method name behave differently depending on the object's type. In C++, runtime polymorphism works by making the base class method virtual and then override-ing it in the derived class.
cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape* shape1 = new Circle();
Shape* shape2 = new Square();
shape1->draw();
shape2->draw();
delete shape1;
delete shape2;
return 0;
}Shape* pointer refers to Circle and Square objects. When draw() is called, the Circle or Square version runs depending on the actual object type. That's thanks to virtual.
You should see
Drawing a circle Drawing a squareInfo
Polymorphism is incredibly useful for structures where types differ but the action stays the same — think game objects, UI components, payment providers, notification channels, and the like.