RTTI (Run-time type Information) in C++ with example

Hello everyone, in this tutorial, we will learn about Run-Time Type Information(RTTI) in C++. This mechanism helps us to expose information about the data type of an object during the execution of the program. We can use the dynamic_cast operator for this purpose which is used for the conversion of polymorphic types. The RTTI mechanism works only when the class has at least one virtual function.

To know more about virtual function, read this.

See the below code.

#include <iostream>
using namespace std;

class parent{

};

class child : public parent{
};

int main()
{
  parent* p = new child;
  child* c = dynamic_cast<child*> (p);
  
  if(c != NULL)
  {
    cout << "The mechanism works.\n";
  }
  else
  {
    cout << "Casting parent* to child* unsuccessful.\n";
  }
  return 0;
}

Output:

cannot dynamic_cast 'p' (of type 'class parent*') to type 'class child*' (source type is not polymorphic)

The above code results in an error as there is no virtual function. Now have a look at the below code which has a virtual function.

#include <iostream>
using namespace std;

class parent{
  virtual void virtual_fun(){}
};

class child : public parent{
};

int main()
{
  parent* p = new child;
  child* c = dynamic_cast<child*> (p);
  
  if(c != NULL)
  {
    cout << "The mechanism works.\n";
  }
  else
  {
    cout << "Casting parent* to child* unsuccessful.\n";
  }
  return 0;
}

Output:

The mechanism works.

As you can see, now the code executes successfully.

Also read: static_cast and dynamic_cast in C++

Leave a Reply

Your email address will not be published.