6

What is runtime type control in C++?

josephthomas
  • 3,256
  • 15
  • 20
gopal
  • 3,681
  • 5
  • 24
  • 25
  • http://stackoverflow.com/questions/351845/finding-the-type-of-an-object-in-c/351865#351865 have a look at this – yesraaj Sep 11 '09 at 10:15

5 Answers5

4

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);
}
Synxis
  • 9,236
  • 2
  • 42
  • 64
Naveen
  • 74,600
  • 47
  • 176
  • 233
4

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

Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93
2

It's dynamic_cast functionality - your code can detect at runtime if a given pointer or reference is really bound to an object of type you expect.

sbi
  • 219,715
  • 46
  • 258
  • 445
sharptooth
  • 167,383
  • 100
  • 513
  • 979
2

The correct name of this is Run-time type information (RTTI).

RED SOFT ADAIR
  • 12,032
  • 10
  • 54
  • 92
0

You can take a Interface* and "ask" c++ to what type of object the pointer points. To my knowledge, this relies on runtime meta information, that needs a few cycles for storing and searching such information.

Look at the "typeid" keyword. It provides the most magic.

dynamic_cast only uses RTTI, typeid with std::type_info seems to me more like the "real thing".

AndreasT
  • 9,417
  • 11
  • 46
  • 60