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:
Include the
<typeinfo>
header file: In order to use thetypeid
operator and thetype_info
class, you need to include the<typeinfo>
header file in your code.Use the
typeid
operator: Thetypeid
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 thetypeid
operator.Retrieve the type name using the
name()
member function: Thetypeid
operator returns atype_info
object, which represents the type of the object. To retrieve the type name as a string, you can use thename()
member function of thetype_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.