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.
Runtime polymorphism in 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.
Animal with a virtual function sound(). The derived class Dog changes the sound.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; } };
Animal* points to a Dog object. Calling sound() runs the Dog version because of runtime polymorphism.Animal* pet = new Dog();
pet->sound();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.
#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; }
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.
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.