C++ Reference ยท Keywords and Statements
The typeid operator
Reference for C++ typeid and std::type_info: finding the dynamic type of polymorphic objects, comparing types, name() output, type_index and when to avoid RTTI.
typeid returns a reference to a std::type_info object (from <typeinfo>) describing the type of its operand. It is part of C++'s runtime type information (RTTI), together with dynamic_cast. The operand can be a type name or an expression.
The important rule: for an expression whose static type is a polymorphic class (it has at least one virtual function), typeid gives the dynamic type of the object the expression refers to. For everything else it gives the static type, resolved at compile time and without evaluating the expression.
#include <typeinfo> const std::type_info& t = typeid(*animalPtr); // dynamic type: Dog, Cat, ...
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
typeid(type) typeid(expression)
Returns: const std::type_info& that lives until the program ends.
std::type_info member |
Description |
|---|---|
operator==, operator!= |
Compare two types for identity (C++20 removes != in favor of rewritten ==) |
before(other) |
Implementation-defined collation order |
hash_code() |
A hash, equal for equal types within one run |
name() |
Implementation-defined name; GCC and Clang return a mangled form |
Errors: typeid(*p) where p is a null pointer to a polymorphic type throws std::bad_typeid. Using typeid without including <typeinfo> is ill-formed.
Usage notes
typeidignores top-levelconst/volatileand references (typeid(const int&) == typeid(int)).- The operand of
typeidis evaluated only when it is a glvalue of polymorphic class type; otherwise it is unevaluated. - Never compare
name()strings across compilers or rely on them for display. To get a readable name on GCC or Clang useabi::__cxa_demangle(non-portable) or a library. std::type_infois neither copyable nor movable. Storestd::type_index(from<typeindex>) in containers; it is hashable and orderable.- RTTI can be disabled (
-fno-rttiin GCC and Clang,/GR-in MSVC); thentypeidon polymorphic expressions anddynamic_castdo not work. - Using
typeidto branch on concrete types (if (typeid(*p) == typeid(Dog))) is usually a design smell. Prefer virtual functions orstd::variantwithstd::visit.dynamic_castalso accepts derived classes, whereastypeid ==tests for an exact type. - For compile-time type checks, use
std::is_same_v, concepts ordecltype, nottypeid.