What is the typeid operator in C++?

The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or reference.

The typeid operator returns an lvalue of type const type_info that represents the type of our value.

An lvalue has an address that your program can access. Examples of lvalue expressions include variable names, const variables, array elements, function calls that return an lvalue​ reference, bit-fields, unions, and class members.

You must include the standard template library header <typeinfo> to use the typeid operator.

Code

The code below further clarifies how to use the typeid operator with different data types.

Note: Since the output for typeid is implementation dependant, the numbers in our output represent the number of characters in the string, while P stands for ​pointer. P7Derived means that the type is a pointer to the class Derived.

#include <iostream>
#include <typeinfo>
class Base {
public:
virtual void myfunc() {}
};
class Derived : public Base {};
using namespace std;
int main() {
Derived* pd = new Derived;
Base* pb = pd;
cout << typeid( pb ).name() << endl; //prints "P4Base"
cout << typeid( *pb ).name() << endl; //prints "7Derived"
cout << typeid( pd ).name() << endl; //prints "P7Derived"
cout << typeid( *pd ).name() << endl; //prints "7Derived"
int i;
cout << typeid(int).name() << endl; //prints "i"
delete pd;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved