ProAnswers.org

What is RTTI in cpp?

2 Likes

Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++.

The dynamic_cast<> operation and typeid operator in C++ are part of RTTI.

With C++ run-time type information, you can perform safe typecasts and manipulate type information at run time.

RTTI is available only for classes which are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because base classes must have a virtual destructor to allow objects of derived classes to perform proper cleanup if they are deleted from a base pointer.

RTTI is optional with some compilers—you choose at compile time whether to include the function. There may be a cost to making RTTI available even if the program does not use it.

example:

class base
{
virtual ~base(){}
};

class derived : public base
{
public:
virtual ~derived(){}
int compare (derived &ref);
};

int my_comparison_method_for_generic_sort (base &ref1, base &ref2)
{
derived & d = dynamic_cast(ref1); // RTTI used here
// RTTI enables the process to throw a bad_cast exception
// if the cast is not successful
return d.compare (dynamic_cast(ref2));
}