What is RTTI for?
The intent of RTTI is to provide a standard way for a program to determine the type of object during runtime.
How Does RTTI Work?
- The dynamic_cast operator generates a pointer to a derived type from a pointer to a base type, if possible. Otherwise, the operator returns 0, the null pointer.
- The typeid operator returns a value identifying the exact type of an object.
- A type_info structure holds information about a particular type.
Caution
RTTI works only for classes that have virtual functions.
class Grand{has virtual methods};
class Superb: public Grand{...};
class Magnificent : public Superb{...};
Grand* pg = new Grand;
Superb * pm = dynamic_cast<Superb *>(pg);
// This code asks whether the pointer pg can be type cast safely to the type Superb*. If it can, the operator renturns the address of the object. Otherwise it returns 0, the null pointer.
You can invoke the Say() function safely:
if(ps = dynamic_cast<Superb *>(pg))
ps->Say();
The typeid operator and type_info Class
The typeid operator returns a reference to a type_info object, where type_info is a class defined in the typeinfo header file (formerly typeinfo.h). The type_info class overloads the == and != operators so that you can use these operators to compare types.
For example, the following expression evalluates to the bool value true if
pg points to a magnificent object and to false otherwise:
typeid(Magnificent) == typeid(*pg);
// if pg happens to be a null pointer, the program throws a bad_typeid exception.
cout<< typeid(*pg).name() <<"\n";