The examples in Figure 1 use
the typeid operator in expressions that
compare the runtime type of objects in the employee class
hierarchy: Figure 1. Examples of typeid operator
in Expressions.
// ...
employee *pe = new manager;
employee& re = *pe;
// ...
typeid(pe) == typeid(employee*) // 1.True - not a polymorphic type1
typeid(&re) == typeid(employee*) // 2.True - not a polymorphic type2
typeid(*pe) == typeid(manager) // 3.True - *pe represents a polymorphic type3
typeid(re) == typeid(manager) // 4.True - re represents the object manager3
typeid(pe) == typeid(manager*) // 5.False - static type of pe returned4
typeid(pe) == typeid(employee) // 6.False - static type of pe returned4
typeid(pe) == typeid(manager) // 7.False - static type of pe returned4
typeid(*pe) == typeid(employee) // 8.False - dynamic type of expression is manager
typeid(re) == typeid(employee) // 9.False - re actually represents manager
typeid(&re) == typeid(manager*) //10.False - manager* not the static type of re
// ...
Note:
In the first comparison, pe is a pointer (that
is, not a polymorphic type); therefore, the expression typeid(pe) returns
the static type of pe, which is equivalent to employee*.
In the second expression, re represents the addess
of the object referred to (that is, not a polymorphic type); therefore,
the expression typeid(re) returns the static type
of re, which is a pointer to employee.
In the third and fourth comparisons, the type returned by typeid represents
the dynamic type of the expression only when the expression represents
a polymorphic type.
Comparisons 5, 6, and 7 are
false because it is the type of the expression (pe)
that is examined, not the type of the object pointed to by pe.
These examples do not directly manipulate type_info objects.
Using the typeid operator with built-in
types requires interaction with type_info objects:
Figure 2. Examples of typeid operators