top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of RTTI in C++ ?

+3 votes
384 views

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

posted Sep 8, 2013 by Vimal Kumar Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

RTTI (Run-time type information) is available only for the classes which have at least one virtual function.

For example, dynamic_cast uses RTTI and following program fails with error “cannot dynamic_cast b’ (of typeclass B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.

#include<iostream>

using namespace std;

class B { };
class D: public B {};

int main()
{
  B *b = new D;
  D *d = dynamic_cast<D*>(b);
  if(d != NULL)
    cout<<"works";
  else
    cout<<"cannot cast B* to D*";
  getchar();
  return 0;
}

Adding a virtual function to the base class B makes it working.

#include<iostream>

using namespace std;

class B { virtual void fun() {} };
class D: public B { };

int main()
{
  B *b = new D;
  D *d = dynamic_cast<D*>(b);
  if(d != NULL)
    cout<<"works";
  else
    cout<<"cannot cast B* to D*";
  getchar();
  return 0;
}
answer Nov 12, 2014 by Manikandan J
Similar Questions
+7 votes

In lot of C++ code in my company I see extern C code something like

extern "C"
{
    int sum(int x, int y)
    {
        return x+y;
    }
}

Please explain the significance of this?

+3 votes

Please provide some details on the static class variable, how it works and any example would be great.

...