RTTI (Run-time type Information) in C++ program

C++Server Side ProgrammingProgramming

In this section, we will see what is the RTTI (Runtime Type Information) in C++. In C++ the RTTI is a mechanism, that exposes information about an object’s datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing.

In the following example, the first code will not work. It will generate an error like “cannot dynamic_cast base_ptr (of type Base*) to type ‘class Derived*’ (Source type is not polymorphic)”. This error comes because there is no virtual function in this example.

Example Code

#include<iostream>
using namespace std;
class Base { };
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}

Now after adding a virtual method, it will work.

Example Code

#include<iostream>
using namespace std;
class Base {
   virtual void function() {
      //empty function
   }
};
class Derived: public Base {};
int main() {
   Base *base_ptr = new Derived;
   Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
   if(derived_ptr != NULL)
      cout<<"It is working";
   else
      cout<<"cannot cast Base* to Derived*";
   return 0;
}

Output

It is working
raja
Published on 09-Apr-2019 13:13:28
Advertisements