typeid().name() in c++
typeid().name()
is an operator in C++ that is used to retrieve the name of a data type at runtime. It returns a const char* that represents the name of the type. Here is an explanation of each step involved in using typeid().name()
:
Step 1: Include the necessary header file
To use typeid().name()
, you need to include the <typeinfo>
header file in your C++ program. This header file contains the necessary functions and types for type identification.
Step 2: Use the typeid
operator
To retrieve the name of a data type, you need to use the typeid
operator followed by the object or type you want to identify. For example, if you have an object obj
of type MyClass
, you can use typeid(obj)
to get the type information.
Step 3: Access the name using the name()
function
Once you have used the typeid
operator, you can access the name of the type using the name()
function. This function returns a const char* that represents the name of the type.
Step 4: Store or print the name
You can store the name of the type in a variable of type const char*
or directly print it using cout
or any other output mechanism.
Here is an example of using typeid().name()
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 include the necessary header files <iostream>
and <typeinfo>
. We then declare an int
variable num
. Using typeid(num)
, we obtain the type information for num
and assign it to a const std::type_info&
variable type
. Finally, we print the name of the type using type.name()
.
The output of this program will vary depending on the compiler and platform, but it might be something like:
Type name: int
This indicates that the type of the num
variable is int
.