typeid
In C++, the typeid keyword is used to determine the class of an object at runtime. It returns a reference to type_info[1]. The use of typeid is often preferred over dynamic_cast<class_type> in situations where just the class information is needed, because typeid is a constant-time procedure, whereas dynamic cast must traverse the class derivation lattice of its argument at runtime[2].
Objects of class bad_typeid are thrown when typeid is called on a dereferenced null pointer. The class is derived from exception, and thrown by typeid and others.
It is generally only useful to use typeid on the dereference of a pointer or reference (i.e. typeid(*ptr) or typeid(ref)) to an object of polymorphic class type (a class with at least one virtual function). This is because these are the only expressions that are associated with run-time type information. The type of any other expression is statically known at compile time.
Example
<source lang="cpp">
- include <iostream>
- include <typeinfo> //for 'typeid' to work
class Person { public:
// ... Person members ...
virtual ~Person() {}
};
class Employee : public Person {
// ... Employee members ...
};
int main () {
Person person;
Employee employee;
Person *ptr = &employee;
// The string returned by typeid::name is implementation-defined
std::cout << typeid(person).name() << std::endl; // Person (statically known at compile-time)
std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
std::cout << typeid(ptr).name() << std::endl; // Person * (statically known at compile-time)
std::cout << typeid(*ptr).name() << std::endl; // Employee (looked up dynamically at run-time
// because it is the dereference of a
// pointer to a polymorphic class)
}
</source> Output (exact output varies by system):
Person Employee Person* Employee
See also
References
- ↑ C++ standard (ISO/IEC14882) section 5.2.8 [expr.typeid]
- ↑ Kalev, Danny. Performance of typeid vs. dynamic_cast<> , 1999-02-25. Retrieved on 2009-02-22.