All Courses
OOP: POLYMORPHISM

What is Polymorphism?

Polymorphism means one interface can have many implementations.

In C++, polymorphism appears mainly in two forms:

  • Compile-time polymorphism.
  • Runtime polymorphism.

Everyday Meaning

Suppose every shape has a draw() behavior.

Circle.draw()    -> draws a circle
Rectangle.draw() -> draws a rectangle
Line.draw()      -> draws a line

The method name is the same, but the behavior changes according to the object.

Why Polymorphism Is Useful

Without polymorphism, code often becomes full of manual type checks:

// if shape is circle, draw circle
// if shape is rectangle, draw rectangle
// if shape is triangle, draw triangle

With polymorphism, you can write:

shape->draw();

and the correct version runs.

Complete Runtime Example

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() const {
        cout << "Animal sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() const override {
        cout << "Bark" << endl;
    }
};

class Cat : public Animal {
public:
    void sound() const override {
        cout << "Meow" << endl;
    }
};

int main() {
    Dog dog;
    Cat cat;

    Animal* animal;

    animal = &dog;
    animal->sound();

    animal = &cat;
    animal->sound();

    return 0;
}

Output:

Bark
Meow

What To Notice

The pointer type is Animal*.

The actual object is sometimes Dog and sometimes Cat.

Because sound() is virtual, the function call depends on the actual object.

Viva Answer

Polymorphism means the same interface can behave in different ways. In C++, compile-time polymorphism is achieved using function overloading and operator overloading, while runtime polymorphism is achieved using inheritance, virtual functions, overriding, and base-class pointers or references.

Quick Check

  1. What does polymorphism mean?
  2. What are the two main types of polymorphism in C++?
  3. Why does animal->sound() call different functions in the example?