Thuta Learning
AdvancedProgrammingbeginner

Polymorphism

Relax. We'll talk through this in plain words — no textbook voice.

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 square

Info

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.

Easy traps

  • If the base class method isn't marked virtual, the base class version can run instead of the derived class version. Using override lets the compiler catch typos and errors for you.