C++ typeid Operator: Usage & Examples

In C++, typeid is an operator used to identify the actual type of an expression.

The typeid operator can take an expression as a parameter and return a std::type_info object that contains information about the type represented by the expression. Including the header file is necessary to use the typeid operator.

For example, the following code demonstrates how to use the typeid operator:

#include <iostream>
#include <typeinfo>

int main() {
    int i = 5;
    double d = 3.14;
    
    const std::type_info& iType = typeid(i);
    const std::type_info& dType = typeid(d);
    
    std::cout << "i is of type: " << iType.name() << std::endl;
    std::cout << "d is of type: " << dType.name() << std::endl;
    
    return 0;
}

The output will be:

i is of type: int
d is of type: double

It is important to note that the name() function of the std::type_info object returned by the typeid operator returns a string representing the type name. The format and content of this string may vary depending on the compiler. Therefore, the type name should be seen as information for debugging purposes and not as part of the program logic.

bannerAds