Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

typeid — type identification

The typeid operator exposes type information. For a polymorphic glvalue it identifies the dynamic type; otherwise it uses the static type.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

typeid(expression)
typeid(type-id)

Use typeid(expression) or typeid(type-id) after including <typeinfo>. The result is an lvalue of type const std::type_info. Compare results using ==; the text returned by .name() is implementation-defined, so it is not a portable identifier.

For a polymorphic glvalue, the operator determines the dynamic type and evaluates its operand. Otherwise, the operand is unevaluated and the result describes its static type. Thus typeid(ref) identifies Derived, but typeid(&ref) describes Base*, and typeid(++n) does not increment n.

References and top-level const and volatile do not distinguish results: typeid(const int&) == typeid(int). Pointee qualifiers remain significant. Class types must be complete. For polymorphic Base, typeid(*p) throws std::bad_typeid if p is null.

During construction or destruction, applying typeid to the object being constructed or destroyed identifies the current constructor's or destructor's class, not a more-derived class. The operand's static type must then be that class or one of its bases; otherwise behavior is undefined.

Examples

#include <iostream>
#include <typeinfo>

struct Base { virtual ~Base() = default; };
struct Derived : Base {};

int main() {
    Derived object;
    Base& ref = object;
    int n = 0;

    std::cout << std::boolalpha;
    std::cout << (typeid(ref) == typeid(Derived)) << '\n';
    std::cout << (typeid(&ref) == typeid(Base*)) << '\n';
    std::cout << (typeid(++n) == typeid(int)) << ' ' << n << '\n';
}

Result

true
true
true 0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources