C++ Polymorphism

C++ Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Like we specified in the previous chapter, Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.


1. Compile-Time vs Run-Time Polymorphism

There are two main types of polymorphism in C++:

  1. Compile-Time Polymorphism: Achieved using Function Overloading and Operator Overloading.
  2. Run-Time Polymorphism: Achieved using Virtual Functions and method overriding.

We will focus on Run-Time Polymorphism here, which relies on base class pointers pointing to derived class objects.


2. Virtual Functions (Method Overriding)

Consider a base class Animal that has a method animalSound(). Derived classes of Animals could be Pig, Cat, Dog, etc. They should all have their own specific implementation of an animal sound.

To achieve true polymorphism, we use the virtual keyword in the base class.

Polymorphism Example

#include <iostream>
using namespace std;

// Base class class Animal { public: // By making this 'virtual', we tell the compiler to decide // at run-time which version of the function to call. virtual void animalSound() { cout << "The animal makes a sound \n"; } };

// Derived class class Pig : public Animal { public: // Overriding the base class method void animalSound() override { cout << "The pig says: wee wee \n"; } };

// Derived class class Dog : public Animal { public: void animalSound() override { cout << "The dog says: bow wow \n"; } };

int main() { Animal* myAnimal; // Create a base class pointer Pig myPig; Dog myDog;

// The base class pointer can point to derived class objects! myAnimal = &myPig; myAnimal->animalSound(); // Outputs: The pig says: wee wee

myAnimal = &myDog; myAnimal->animalSound(); // Outputs: The dog says: bow wow

return 0; }

Why is this useful?

Imagine writing a game loop. You have a list of pointers to Enemy objects. Some are Goblins, some are Dragons. Instead of checking their type, you just loop through the list and call enemy->attack(). Polymorphism ensures that the Goblin executes the Goblin attack code, and the Dragon executes the Dragon attack code automatically!


Exercise

?

Which keyword is used in a base class to allow method overriding and run-time polymorphism?