Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run-time type information in C++

Tags:

c++

rtti

What is runtime type control in C++?

like image 631
gopal Avatar asked Sep 11 '09 09:09

gopal


People also ask

What is run-time type identification?

Run-time type identification (RTTI) lets you find the exact type of an object when you have only a pointer or reference to the base type. This can be thought of as a “secondary” feature in C++, a pragmatism to help out when you get into messy situations.

Which control helps you to type information during the runtime?

In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object's data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.

Is C++ runtime type?

In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime.

Why do we need RTTI?

RTTI, Run-Time Type Information, introduces a [mild] form of reflection for C++. It allows to know for example the type of a super class, hence allowing to handle an heterogeneous collection of objects which are all derived from the same base type. in ways that are specific to the individual super-classes.


2 Answers

It enables you to identify the dynamic type of a object at run time. For example:

class A
{
   virtual ~A();
};

class B : public A
{
}

void f(A* p)
{
  //b will be non-NULL only if dynamic_cast succeeds
  B* b = dynamic_cast<B*>(p);
  if(b) //Type of the object is B
  {
  }
  else //type is A
  { 
  }
}

int main()
{
  A a;
  B b;

  f(&a);
  f(&b);
}
like image 143
Naveen Avatar answered Sep 19 '22 23:09

Naveen


It is not just about dynamic_cast, but the entire RTTI is part of it. The best place to learn about RTTI is section 15.4 of the C++ Programming Language by Bjarne Stroustrup

like image 41
Vijay Mathew Avatar answered Sep 17 '22 23:09

Vijay Mathew