C++ typeid Explained: Purpose and Usage
The typeid in C++ is an operator used to retrieve the type information of an expression. It returns a std::type_info object that contains the type information of the expression, including the name of the type.
The typeid is commonly used with dynamic_cast and std::type_info to identify the actual type of an object at runtime, allowing for polymorphism.
Here is an example of how to use typeid:
#include <iostream>
#include <typeinfo>
class Base {
virtual void foo() {}
};
class Derived : public Base {};
int main() {
Base* basePtr = new Derived();
// 使用typeid获取basePtr所指对象的类型信息
const std::type_info& type = typeid(*basePtr);
// 打印类型的名称
std::cout << "Object type: " << type.name() << std::endl;
// 使用typeid进行类型判断
if (type == typeid(Base)) {
std::cout << "Object is of type Base" << std::endl;
}
else if (type == typeid(Derived)) {
std::cout << "Object is of type Derived" << std::endl;
}
delete basePtr;
return 0;
}
The output result:
Object type: class Derived
Object is of type Derived
In the example above, typeid(*basePtr) returns a type_info object with the name “class Derived”, indicating that the actual type of the object pointed to by basePtr is Derived.