The typeid operator identifies the exact type of an object that is given a pointer to a base class. It is typically used to gain access to information needed to perform some operation where no common interface can be assumed for every object manipulated by the system. Object I/O and database systems often need to perform services on objects where no virtual function is available to do so. The typeid operator enables this.
A typeid operation has this form:
>>-typeid--(--type_name--expression--)-------------------------><
The result of a typeid operation has type const type_info&.
Table 32 summarizes the results of various typeid
operations.
Operand | typeid Returns |
---|---|
type_name | A reference to a type_info object that represents it. |
expression | A reference to a type_info that represents the type of the expression. |
Reference to a polymorphic type | The type_info for the complete object referred to. |
Pointer to a polymorphic type | The dynamic type of the complete object pointed to.
|
Nonpolymorphic type | The type_info that represents the static type of the
expression.
|
The examples in Figure 331 use the typeid operator in expressions that compare the run-time type of objects in the employee class hierarchy:
Figure 331. 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 // ... |
Notes:
These examples do not directly manipulate type_info objects. Using the typeid operator with built-in types requires interaction with type_info objects:
Figure 332. Examples of typeid operators
|
To use the typeid operator in Run-Time Type Identification (RTTI) you must include the C++ standard header <typeinfo.h> This header defines these classes:
The copy constructor and the assignment operator for the class type_info are private; objects of this type cannot be copied.
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.