0
0
C++programming~7 mins

Runtime polymorphism in C++

Choose your learning style9 modes available
Introduction

Runtime polymorphism lets a program decide which function to use while it is running, not before. This helps make programs flexible and easy to change.

When you want different objects to respond differently to the same function call.
When you have a base class pointer or reference but want to call derived class functions.
When you want to write code that works with many types of objects without changing it.
When you want to add new behaviors without changing existing code.
When you want to use interfaces or abstract classes to design your program.
Syntax
C++
class Base {
public:
    virtual void show() {
        // base class version
    }
};

class Derived : public Base {
public:
    void show() override {
        // derived class version
    }
};

The keyword virtual before a function in the base class tells C++ to use runtime polymorphism.

The override keyword in the derived class helps catch mistakes and shows you are replacing the base function.

Examples
This example shows a base class Animal with a virtual function sound(). The derived class Dog changes the sound.
C++
class Animal {
public:
    virtual void sound() {
        std::cout << "Some sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Bark" << std::endl;
    }
};
Here, a pointer of type Animal* points to a Dog object. Calling sound() runs the Dog version because of runtime polymorphism.
C++
Animal* pet = new Dog();
pet->sound();
Sample Program

This program creates two shapes: a circle and a square. Both are accessed through pointers of the base class Shape. When draw() is called, the program decides at runtime which version to use, showing runtime polymorphism.

C++
#include <iostream>

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a square" << std::endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    Shape* shape2 = new Square();

    shape1->draw();  // Calls Circle's draw
    shape2->draw();  // Calls Square's draw

    delete shape1;
    delete shape2;
    return 0;
}
OutputSuccess
Important Notes

Always declare base class functions as virtual to enable runtime polymorphism.

Use override in derived classes to avoid mistakes and improve code clarity.

Remember to delete objects created with new to avoid memory leaks.

Summary

Runtime polymorphism lets programs choose the right function during execution.

Use virtual functions in base classes and override them in derived classes.

This helps write flexible and reusable code that works with many object types.