C++ Programming Guide

typeid Operator

The typeid operator produces a reference to an object of class type_info, which describes the most-derived type of the object. To make use of the typeid() function, the source code must #include the <typeinfo> header file. The primary value of this operator/class combination is in comparisons. In such comparisons, the top-level const and volatile qualifiers are ignored, as in the following example. Note that, in this example, A and B are types which have default constructors.


#include <typeinfo>
#include <assert.h>
void use_of_typeinfo( )
{ 
      A a1;
      const A a2;
      assert( typeid(a1) == typeid(a2) );
      assert( typeid(A)  == typeid(const A) );
      assert( typeid(A)  == typeid(a2) );
      assert( typeid(A)  == typeid(const A&) );
      B b1;
      assert( typeid(a1) != typeid(b1) );
      assert( typeid(A)  != typeid(B) ); 
}

The typeid operator raises a bad_typeid exception when given a null pointer.