Run-Time Polymorphism

Run-time polymorphism, also known as dynamic polymorphism, occurs when a function call to a derived class object is resolved at runtime. It allows for behavior that varies depending on the type of object being referred to at runtime.

Key Concepts

  1. Virtual Functions:
    • Functions defined in a base class using the virtual keyword.
    • Enable derived classes to override base class methods.
  2. Function Overriding:
    • A derived class provides a specific implementation of a function already defined in its base class.
    • Achieved by redefining the virtual function in the derived class.
  3. Base Class Pointer:
    • A pointer of the base class type can point to objects of the derived class.
    • Calls to overridden functions are resolved at runtime.

Example

#include <iostream>
using namespace std;

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

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

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

int main() {
    Animal* a1 = new Dog();
    Animal* a2 = new Cat();

    a1->sound();  // Output: Barking
    a2->sound();  // Output: Meowing

    delete a1;
    delete a2;
    return 0;
}