The typeid operator (C++ only)

The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.

Read syntax diagramSkip visual syntax diagramtypeid operator syntax
 
>>-typeid--(--+-expr------+--)---------------------------------><
              '-type-name-'
 

The typeid operator requires runtime type information (RTTI) to be generated, which must be explicitly specified at compile time through a compiler option.

The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr. You must include the standard template library header <typeinfo> to use the typeid operator.

If expr is a reference or a dereferenced pointer to a polymorphic class, typeid will return a type_info object that represents the object that the reference or pointer denotes at run time. If it is not a polymorphic class, typeid will return a type_info object that represents the type of the reference or dereferenced pointer. The following example demonstrates this:

#include <iostream>
#include <typeinfo>
using namespace std;

struct A { virtual ~A() { } };
struct B : A { };

struct C { };
struct D : C { };

int main() {
  B bobj;
  A* ap = &bobj;
  A& ar = bobj;
  cout << "ap: " << typeid(*ap).name() << endl;
  cout << "ar: " << typeid(ar).name() << endl;

  D dobj;
  C* cp = &dobj;
  C& cr = dobj;
  cout << "cp: " << typeid(*cp).name() << endl;
  cout << "cr: " << typeid(cr).name() << endl;
}

The following is the output of the above example:

ap: B
ar: B
cp: C
cr: C

Classes A and B are polymorphic; classes C and D are not. Although cp and cr refer to an object of type D, typeid(*cp) and typeid(cr) return objects that represent class C.

Lvalue-to-rvalue, array-to-pointer, and function-to-pointer conversions will not be applied to expr. For example, the output of the following example will be int [10], not int *:

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
  int myArray[10];
  cout << typeid(myArray).name() << endl;
}

If expr is a class type, that class must be completely defined.

The typeid operator ignores top-level const or volatile qualifiers.

Related information