RTTI (RunTime Type Information) in C++ (original) (raw)

Last Updated : 13 Dec, 2025

RTTI (Run-Time Type Information) allows a C++ program to identify the actual type of an object while the program is running. It plays an important role when working with inheritance and polymorphism.

Runtime Cast

A runtime cast is a type conversion that checks its validity during program execution, typically used to safely downcast a base class pointer or reference to a derived class in an inheritance hierarchy.

Upcasting

#include using namespace std;

class Base { public: void show() { cout << "Base class\n"; } };

class Derived : public Base { public: void show() { cout << "Derived class\n"; } };

int main() { Derived d;

// Upcasting: Derived object treated as Base
Base *b = &d;

b->show(); 
return 0;

}

`

Downcasting

#include using namespace std;

class Base { public: virtual void dummy() { } // Make Base polymorphic };

class Derived : public Base { public: void show() { cout << "Derived class\n"; } };

int main() { Base *b = new Derived;

// Downcasting: Convert Base pointer back to Derived pointer
Derived *d = dynamic_cast<Derived *>(b);

if (d != nullptr)
    d->show();
else
    cout << "Cannot cast";

delete b;
return 0;

}

`