How Does RTTI Work?

C++ has three components supporting RTTI:

• 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.

You can use RTTI only with a class hierarchy that has virtual functions. The reason for this is that these are the only class hierarchies for which you should be assigning the addresses of derived objects to base-class pointers.


RTTI works only for classes that have virtual functions.

Let’s examine the three components of RTTI.

The dynamic_cast Operator

The dynamic_cast ...

Get C++ Primer Plus now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.