Most c++ STL classes have easy to understand implementation. However, the type_info
class is confusing. How does some code know the info of a class?
My first theory is that the type_info
class gets the information from the compiler (which means that the STL has some integration with the compiler).
It could also be some obscure c++ syntax that I don’t know of, but am not too sure about this theory.
type_info
is just a standard library class that provides type information. Objects of this class are returned by the typeid
operator.
Of greatest interest is not the class itself, but the RTTI (Run-Time Type Identification) implementation. This is a purely compiler dependent feature, part of the ABI (Application Binary Interface).
In brief, the compiler stores type information for each polymorphic type along with its vtable or VMT (Virtual Method Table). This information is per-type, not per-object and used by typeid
and by dynamic_cast
. The type_info
class is just an interface provided to the end user, it has an internal implementation depending on the compiler.
Different compilers implement different ABIs. Modern gcc and clang compilers implement Itanium C++ ABI, which describes all the details of RTTI and the rest. Microsoft Visual C++ ABI is undocumented.
A good article that describes C++ vtables and covers RTTI: Shahar Mike - C++ vtables.