RTTI - Run Time Type Information in C++



In C++, RTTI (Run-time type information) is a process that disclose information about an object data types at runtime and available one for the classes that have at least one virtual function. It allow the type of an object to be determine during the program execution.

Runtime Casts

The runtime cast checks that the cast is valid. It is the simplest approach to confirm the runtime type of an object using a pointer or reference. It is especially beneficial when we cast a pointer from a base class to a derived type. There are two types of casting:

  • Upcasting: When a pointer or reference to a derived class object is treated as a base class pointer.
  • Downcasting: When a base class pointer or reference is converted to a derived class pointer.

Example of Run-time Type Information Without Virtual Functions

The following C++ program demonstrates run-time type information (RTTI) but without virtual functions:

#include <iostream>
using namespace std;

class Base {};

class Derived : public Base {};
 
// Driver Code
int main()
{
   // Base class pointer
   Base* b = new Derived;
   // Derived class pointer
   Derived* d = dynamic_cast<Derived*>(b);
   if (d != NULL)
      cout << "works";
   else
      cout << "cannot cast Base* to Derived*";
   getchar();
   return 0;
}

We get the following error because we have not given at least one virtual function to the base class -

cannot 'dynamic_cast' 'b' (of type 'class Base*') to type 'class Derived*' (source type is not polymorphic)
Derived* d = dynamic_cast<Derived*>(b);

Example of Run-time Type Information With Virtual Functions

Here, in this example, we just added a virtual function to the base class "base" to make the previous example run -

#include <iostream>
using namespace std;

class Base {
   virtual void fun() {}
};

class Derived: public Base {};

int main() {
   Base * b = new Derived;
   Derived * d = dynamic_cast < Derived * > (b);
   if (d != NULL)
      cout << "It is working fine";
   else
      cout << "cannot cast Base* to Derived*";
   getchar();
   return 0;
}

Following is the output of the above code -

It is working fine
Updated on: 2025-05-15T15:39:38+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements