[C++] RTTI

RTTI stands for “Run Time Type Identification” and it lets you identify the type of an object at runtime. RTTI is added to C++ in order to support run-time polymorphism. The “dynamic_cast” operator is also directly linked to RTTI.   

 

1. RTTI

C++ implements polymorphism through the use of class inheritance, virtual functions, and base class pointers. A base class pointer might point to objects of the base class or any object derived from that base. So it is important to know what the base pointer actually points to.

This type identification must be made at run time, by using RTTI (Run Time Type Identification).

 

2. Syntax

  • typeid (object)
  • typeid (type-name)

It returns the object of “type_info

class MyClass
{
};

int main()
{
    int i, j;
    MyClass myObj;

    bool b1 = ( typeid (i) == typeid (j) ); // true
    bool b2 = ( typeid (i) == typeid (myObj) ); // false

    cout << b1 << " " << b2 << endl;
    return (EXIT_SUCCESS);
}

 

3. type_info class

The type_info class defines the following public members:

  • bool operator==(const type_info &ob); // override == operator
  • bool operator!=(const type_info &ob); // override != operator
  • const char *name(); // name of the type
class MyBaseClass
{
public:
    virtual void MyFunc() = 0; // make the class polymorphic
};
class MyDerivedClass : public MyBaseClass
{
public:
    virtual void MyFunc() { cout << "Hello" << endl; }
};

int _tmain(int argc, _TCHAR* argv[])
{
  int i = 10;
  double d = 10.5;
  MyBaseClass *myBaseObjPointer;
  MyDerivedClass myDerivedObj, *myDerivedObjPointer;

  cout << typeid(i).name() << endl; // int
  cout << typeid(d).name() << endl; // double
  cout << typeid(myDerivedObj).name() << endl; // class MyDerivedClass

  // Polymorphism
  myDerivedObjPointer = new MyDerivedClass();
  myBaseObjPointer = myDerivedObjPointer;

  cout << typeid(*myBaseObjPointer).name() << endl; // class MyDerivedClass
  cout << typeid(*myDerivedObjPointer).name() << endl; // class MyDerivedClass

  // check ploymorphic base type here...
  if( typeid(*myBaseObjPointer) == typeid(MyDerivedClass) )
  {
    myBaseObjPointer->MyFunc();
  }
  else
  {
    cout << "Not a type of MyDerivedClass" << endl;
  }
  return (EXIT_SUCCESS);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s