Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
typeid
typeinfo

What is the typeid operator in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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;
}

RELATED TAGS

c++
typeid
typeinfo
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring