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
lvaluehas an address that your program can access. Examples oflvalueexpressions include variable names, const variables, array elements, function calls that return anlvalue reference, bit-fields, unions, and class members.
You must include the standard template library header <typeinfo> to use the typeid operator.
The code below further clarifies how to use the typeid operator with different data types.
Note: Since the output for
typeidis implementation dependant, the numbers in our output represent the number of characters in the string, whilePstands for pointer.P7Derivedmeans that the type is a pointer to the classDerived.
#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