Explain Runtime polymorphism with an example.

SOLUTION....

Runtime Polymorphism (Dynamic Polymorphism) in C++

Definition:
Runtime polymorphism lets a call made through a base-class pointer/reference invoke the overridden function of the derived object at runtime. In C++, this is achieved with virtual functions.

How it works (in short):

  • Mark a base-class function as virtual.

  • Override it in derived classes with the same signature (use override).

  • Call through a base pointer/reference; the actual function chosen depends on the dynamic type of the object (late binding).

  • Make destructors virtual in polymorphic bases to avoid resource leaks.

Why use it:
Provides a single interface (base class) for multiple behaviors (derived classes), enabling extensible, clean designs.


#include <iostream>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;  // pure virtual => abstract base
    virtual ~Shape() = default;       // always virtual in polymorphic base
};

class Rectangle : public Shape {
    double w, h;
public:
    Rectangle(double W, double H) : w(W), h(H) {}
    double area() const override { return w * h; }
};

class Triangle : public Shape {
    double b, h;
public:
    Triangle(double B, double H) : b(B), h(H) {}
    double area() const override { return 0.5 * b * h; }
};

int main() {
    Shape* s;                  // base-class pointer

    Rectangle r(10, 5);
    Triangle  t(6, 4);

    s = &r;                    // points to Rectangle
    cout << "Rectangle area: " << s->area() << '\n';

    s = &t;                    // points to Triangle
    cout << "Triangle area:  " << s->area() << '\n';

    return 0;
}

OUTPUT

Key Points (Quick Rules)

  • Use virtual in the base; use override in derived.

  • Call via base pointer/reference for dynamic dispatch.

  • Keep signature identical; return types must be compatible.

  • Prefer a virtual destructor in any class meant for polymorphism.

  • Avoid object slicing (don’t pass/store derived objects by value as base).

 
 

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.