Important:
Ideally, if you need to identify the type of an object you need to revisit your design because most likely you missed something there and you are violating the SOLID rules of OOP.
C++ standard provides dynamic_cast
and typeid
as two ways of determining the type of an object. Both have their advantages and limitations. How they identify the type is an implementation dependent detail but typically they do so by maintaining a pointer to the type information structure in the vtable of an object. If you are completely unaware of what a vtable is, Marshal Clines C++ Faq provides a good explanation here.
You can find the implementation detail used by most compilers in,
Technical Report on C++ Performance
Relevant Extract:
5.3.7 Type Information
Given an object of a polymorphic class (a class with at least one virtual function), a type_info object can be obtained through the use of the typeid operator. In principle, this is a simple operation which involves finding the virtual function table, through that finding the most-derived class object of which the object is part, and then extracting a pointer to the type_info object from that object’s virtual function table (or equivalent).
5.3.8 Dynamic Cast
Given a pointer to an object of a polymorphic class, a cast to a pointer to another base subobject of the same derived class object can be done using a dynamic_cast. In principle, this operation involves finding the virtual function table, through that finding the most-derived class object of which the object is part, and then using type information associated with that object to determine if the conversion (cast) is allowed, and finally performing any required adjustments of the this pointer. In principle, this checking involves the traversal of a data structure describing the base classes of the most derived class. Thus, the run-time cost of a dynamic_cast may depend on the relative positions in the class hierarchy of the two classes involved.