c++ get type name of object

To get the type name of an object in C++, you can use the typeid operator along with the type_info class. Here are the steps to do this:

  1. Include the <typeinfo> header file: In order to use the typeid operator and the type_info class, you need to include the <typeinfo> header file in your code.

  2. Use the typeid operator: The typeid operator is used to retrieve the type information of an object. You need to pass the object whose type you want to retrieve as the operand to the typeid operator.

  3. Retrieve the type name using the name() member function: The typeid operator returns a type_info object, which represents the type of the object. To retrieve the type name as a string, you can use the name() member function of the type_info class.

Here is an example code snippet that demonstrates how to get the type name of an object in C++:

#include <iostream>
#include <typeinfo>

int main() {
    int num = 10;
    const std::type_info& type = typeid(num);
    std::cout << "Type name: " << type.name() << std::endl;

    return 0;
}

In this example, we have an integer variable num. We use the typeid operator to retrieve the type information of num and store it in the type variable. Then, we use the name() member function of the type_info class to retrieve the type name as a string and print it to the console.

When you run this code, it will output the type name of the num variable, which in this case is "int".

Note that the type name returned by type.name() may not be very human-readable, as it is implementation-dependent. It may be a mangled name or an abbreviated version of the actual type name.