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.

Caution

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.