Skip to main content
The typeid operator is a C++ language facility that queries type information at compile-time or runtime. It yields an lvalue of static type const std::type_info representing the exact type of the operand.

Syntax

To use the typeid operator, the <typeinfo> standard library header must be included.

Completeness Requirement

When typeid is applied to a type-id representing a class type, or to an expression whose static type is a class type, that class type must be completely defined. Applying typeid to an incomplete type results in a compilation error.

Evaluation Mechanics

The evaluation strategy of typeid strictly depends on the value category and polymorphism of its operand: 1. Runtime Evaluation (Dynamic Type / RTTI) Runtime evaluation only occurs if the operand is a glvalue expression of a polymorphic class type (a class declaring or inheriting at least one virtual function). The operator inspects the virtual table (vtable) of the object to determine its most derived dynamic type. Because it requires runtime resolution, the expression itself is evaluated. 2. Compile-Time Evaluation (Static Type) For all other operands, typeid is resolved entirely at compile-time based on the static type. This includes:
  • Any type-id.
  • Expressions of non-polymorphic types.
  • prvalue expressions of polymorphic types (e.g., typeid(Base())).
In these compile-time scenarios, the expression is treated as an unevaluated operand; no runtime execution of the expression occurs.

Type Adjustments

Before the std::type_info object is generated, the C++ compiler applies specific type adjustments:
  • Reference Stripping: If the operand is a type-id representing a reference type (T& or T&&), typeid evaluates the referenced type (T). For expression operands, this rule is implicitly satisfied because C++ expressions do not possess reference types; references are dropped during standard expression evaluation before typeid is applied.
  • CV-Qualifier Stripping: Top-level const and volatile qualifiers are ignored. typeid(const T) and typeid(T) yield std::type_info objects that represent the same type and compare equal via operator==. Pointers to const types (const T*), however, retain their constness because the qualifier is not top-level.

Exception Handling

When evaluating a polymorphic glvalue expression at runtime, if the operand is a dereferenced null pointer (e.g., *ptr where ptr evaluates to a null pointer value), the typeid operator throws an exception of type std::bad_typeid. Dereferencing a null pointer in a compile-time evaluated context (such as a non-polymorphic type or a prvalue) does not throw, because the expression is an unevaluated operand.

Syntax Visualization

Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More