C++ provides RTTI (Runtime Type Information ) mechanism by which we can get information of an object or variable at run time. In c++ we can get information about object or variable in two ways

To use typeid() operator  we need to include #include <typeinfo> in the source code. The

typeid

operator returns a

const

reference to a

type_info

object. Below is a simple example of typeid use.

#include<iostream>
#include<typeinfo>

using namespace std;

class A {};

int main()
{
 A a_obj;
 type_info const &tobj = typeid(a_obj);
 cout<<"The object class name is : "<<tobj.name();
 cout<<endl;
 return 0;
}

Output:

The object class name is : 1A

  • The typeid can be used to determine whether two objects are the same type.
  • When
    argument to typeid

    is pointer to a polymorphic class, the result is the type of the most derived object.

#include<iostream>
#include<typeinfo>

using namespace std;

class A
{
public:
virtual ~ A () { }
};              // polymorphic class
class B:public A{};

int main ()
{
 A *a_obj = new B ();
 type_info const &tobj = typeid (*a_obj);
 cout << "The object class name is : " << tobj.name ();
 cout << endl;
return 0;
}
Output:
The object class name is : 1B
  • When the argument to typeid is a pointer to base class which points to derived class and if base class is not polymorphic then result refers to a
    std::type_info

    object representing the static type of the expression. 

#include<iostream>
#include<typeinfo>

using namespace std;

class A
{
public:
~ A () { }
};        // non polymorphic class
class B:public A{}; // non polymorphic

int main ()
{
A *a_obj = new B ();
type_info const &tobj = typeid (*a_obj);
cout << "The object class name is : " << tobj.name ();
cout << endl;
return 0;
}
output:
The object class name is : 1A


Related Contents to follow