Accessing runtime type information

C++ provides an operator called typeid that will return type information about a variable (or a type) at runtime. Runtime Type Information (RTTI) is significant when you use custom types that can be used in a polymorphic way; details will be left until later chapters. RTTI allows you to check at runtime the type of a variable and process the variable accordingly. RTTI is returned through a type_info object (in the <typeinfo> header file):

    cout << "int type name: " << typeid(int).name() << endl;     int i = 42;     cout << "i type name: " << typeid(i).name() << endl;

In both cases, you'll see int printed as the type. The type_info class defines comparison operators (== and !=) so you can compare types:

 auto ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.