Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, August 17, 2026

To design and implement a simple C++ application to demonstrate dynamic polymorphism and Run-Time Type Identification (RTTI).

 

Experiment 6

Aim

To design and implement a simple C++ application to demonstrate dynamic polymorphism and Run-Time Type Identification (RTTI).

Objectives

  • To understand runtime polymorphism.
  • To implement virtual functions.
  • To understand dynamic_cast.
  • To understand typeid and RTTI.

Theory

Dynamic polymorphism occurs when a base-class pointer or reference invokes an overridden function of a derived class at runtime.

RTTI allows the program to determine the actual type of an object during runtime. C++ provides typeid and dynamic_cast for this purpose.

Program

#include <iostream>

#include <typeinfo>

using namespace std;

 

class Shape {

public:

    virtual void display() {

        cout << "Shape\n";

    }

 

    virtual ~Shape() {}

};

 

class Circle : public Shape {

public:

    void display() override {

        cout << "Circle\n";

    }

 

    void circleInfo() {

        cout << "Circle specific function\n";

    }

};

 

class Rectangle : public Shape {

public:

    void display() override {

        cout << "Rectangle\n";

    }

};

 

int main() {

    Shape *ptr;

 

    Circle c;

    Rectangle r;

 

    ptr = &c;

 

    cout << "Dynamic Polymorphism:\n";

    ptr->display();

 

    if (dynamic_cast<Circle*>(ptr))

        cout << "Object is Circle\n";

 

    cout << "Runtime type: "

         << typeid(*ptr).name() << endl;

 

    ptr = &r;

 

    ptr->display();

 

    cout << "Runtime type: "

         << typeid(*ptr).name() << endl;

 

    return 0;

}

Result

Thus, dynamic polymorphism and RTTI using dynamic_cast and typeid were successfully demonstrated.

No comments:

Post a Comment