- Typeid
In
C++ , thetypeid
keyword is used to determine the class of an object atruntime . According to the C++ specification, it returns a reference totype_info
. The use oftypeid
is often preferred overdynamic_cast<"class_type">
in situations where just the class information is needed, becausetypeid
is a constant-time procedure, whereas
must traverse the class derivation lattice of its argument at runtime.dynamic cast Objects of class
bad_typeid
are thrown whentypeid
is called on a dereferenced null pointer. The class is derived fromexception
, and thrown by typeid and others.Note that it is only useful to use typeid on the dereference of a pointer or reference (i.e.
typeid(*ptr)
ortypeid(ref)
) to a polymorphic class (a class with at least one virtual method). 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, and so is not very interesting.Caution: the actual text returned by typeid is platform specific so don't rely on it if attempting to produce platform independent code.
Example
#include
#include//for 'typeid' to workusing namespace std; class Person {public: // ... Person members ... virtual ~Person() {;
class Employee : public Person { // ... Employee members ...};
int main (){ Person person; Employee employee; Person *ptr = &employee;
cout << typeid(person).name() << endl; // Person (statically known at compile-time) cout << typeid(employee).name() << endl; // Employee (statically known at compile-time) cout << typeid(ptr).name() << endl; // Person * (statically known at compile-time) cout << typeid(*ptr).name() << endl; // Employee (looked up dynamically at run-time // because it is the dereference of a pointer to a polymorphic class) return 0;}
Output (exact output varies by system):
Person Employee *Person Employee
See also
*
Run-time type information
Wikimedia Foundation. 2010.