top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is RTTI in C++ and when to use it?

+2 votes
1,237 views
What is RTTI in C++ and when to use it?
posted Apr 8, 2014 by Harshita

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

RTTI (Run-Time Type Information, or Run-Time Type Identification refers to a mechanism that exposes information about an object's data type at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic types. This is a C++ specialization of a more general concept called type introspection.

The dynamic_cast<> operation and typeid operator in C++ are part of RTTI. The C++ run-time type information permits performing safe typecasts and manipulate type information at run time.

class Base
{
public:  
    virtual ~Base(){}
};

class Derived : public Base
{
public:
    Derived() {}
    virtual ~Derived() {}

    int compare (Derived& ref);
};

int myComparisonMethodForGenericSort (Base& ref1, Base& ref2)
{
    Derived& d = dynamic_cast<Derived&>(ref1); //RTTI used here
    //Note: If the cast is not successful, RTTI enables the process to throw a bad_cast exception

    return d.compare (dynamic_cast<Derived&>(ref2));
}

Ref: https://en.wikipedia.org/wiki/Run-time_type_information

answer Apr 8, 2014 by Salil Agrawal
Similar Questions
+3 votes

What is the need of this concept Run Time Type identifier ?

+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...