The Secret Life of C++: Runtime Type Information and Casting

C++ objects in modern runtimes generally know their types, and can use this for a little bit of introspection and for checking for safe casts.

Run time type information allows us to do complicated things at runtime, like dynamic_cast<>.

As we saw in our VTable examples, there is a pointer to a type info structure in every vtable of every class. This allows us to look at this object at runtime and find out details about the class we have. All we have to know is the vtable for an object, and we can, for example, find the name of its type.


Lets look at a quick example that use dynamic_cast<T>.







It's clear that the __dynamic_cast function does most of the work. Let's look at the implementation.


Using RTT directly

We can also use RTTI ourselves to do some cute things, or at least print stuff.





Fork me on GitHub