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.
typeid
can work because RTTI is implemented in the compiler, so asking whether or not to usetypeid
"to implement RTTI" looks confused. What exactly do you mean by "implement RTTI"? – Quickdynamic_cast
andtypeid
depend on the language feature called RTTI. If your source code uses either of them, you need RTTI for the program to compile. However, RTTI demands a small runtime overhead so some compilers allow you to turn it off. This is the reason why we want a common name for "typeid
anddynamic_cast
", instead of just talking about each of them in isolation. – Quickdynamic_cast
will fail if the object is not of the target type. Please ask a new question (with the Ask Question-button) if you want to clear up howdynamic_cast
works, so we can keep the questions and answers on point, and avoid long comment threads :) – Quick