Describe RTTI – Run Time Type Information in C++

(Last Updated On: February 25, 2019)

Answer: RTTI – Run Time Type Information in C++ is a mechanism that allows the type of an object to be determined at run time.

dynamic_cast operator and typeid operator are part of RTTI – Run time type identification in C++.

  • dynamic_cast : Used for type conversion of polymorphic types.
  • typeid operator: Used for identifying the exact type of an object.
[Recommended: Use of RTTI – Dynamic_cast in C++]

RTTI in C++ is available only for classes which are polymorphic which means classes have at least one virtual method.

NOTE: Since RTTI is included in the virtual method table i.e. VTABLE, there should be at least one virtual function. In fact, if we have at least one virtual method in a class, VTABLE will get generated.

 

If we apply RTTI on non-polymorphic class in c++, compiler will flash an error. Consider below example of dynamic_cast on non-polymorphic classes.

/Dynamic_cast works on Polymorphic classes only/