How Does RTTI Work?
C++ has three components supporting RTTI:
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.
typeid operator returns a value identifying the exact type of an object.
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.
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.