Lesson 150 +12 XP

Polymorphism

Polymorphism

Polymorphism means "many forms". It lets the same call behave differently depending on the actual type of the object behind it. It is one of the biggest benefits of inheritance.

One base, several forms

Consider an Animal base and derived classes that each do their own thing:

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

class Pig : public Animal {
public:
  void sound() { cout << "Oink"; }
};

class Dog : public Animal {
public:
  void sound() { cout << "Woof"; }
};

A base pointer can hold any derived object

The core trick: a pointer to the base can point at any derived class:

int main() {
  Animal* a;
  Pig pig;
  Dog dog;

  a = &pig;
  a->sound();   // prints "Oink"

  a = &dog;
  a->sound();   // prints "Woof"
  return 0;
}

The same pointer variable and the same statement a->sound() produce different results. That is polymorphism in action.

No rewriting needed

Add a third derived class and the calling code does not change at all. New behavior slides in through the same base interface.

Many forms at runtime

The base pointer does not know in advance which sound() will run. The call is resolved at runtime, based on the real object behind the pointer. That is why it earns the name "many forms".

TL;DR

  • Polymorphism = one interface, many behaviors.
  • A base pointer can point at any derived object.
  • The same call runs the correct version for the real object.
  • New derived classes fit in without rewriting the caller.
  • Virtual functions make the behavior dynamic.