Jump to content

typeid

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 200.68.94.105 (talk) at 15:50, 6 October 2008. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In C++, the typeid keyword is used to determine the class of an object at runtime. According to the C++ specification, it returns a reference to type_info. 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.

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.

Note that it is only useful to use typeid on the dereference of a pointer or reference (i.e. typeid(*ptr) or typeid(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 <iostream>
#include <typeinfo>  //for 'typeid' to work
using 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