June 15, 2004 10:16 PM
Runtime Type Identification (RTI) wasn't in the original C++ design. It was introduced later by Stroustrup along with Dmitry Lenkov and his colleagues at HP (Lenkov, Mehta, Unni, 1991). In a large project composed of several separately developed parts, at times objects are passed around in such a way that their exact type remains unknown. RTI in C++ enables the programmer to find out about a particular object's type at runtime (duh!) using a runtime-checked pointer conversion (or as C++ aficionado's say, a dynamic_cast).

Imagine a class Human and a class Programmer. Now if we have a pointer to an object of Human and we want to find if the pointer actually points to a Programmer or some other class derived from it because only Programmer object needs to be done something1 to, what would we do? Sure, we could always define specific virtual functions in the base class and then override it in the derived class so that something can be done appropriately. This solution though obvious isn't always feasible because we might not control the definition of the base class.

if (Programmer* coolguy = dynamic_cast<Programmer*>(mysteryobject))
{
  std::cout << "Success, mysteryobject is a Programmer!";
  //use coolguy as a pointer to type Programmer
}
else
{
  std::cout << "Awww... mysteryobject is not a Programmer.";
}

dynamic_cast returns 0 if the object is not of class Programmer or derived from it. Otherwise it returns a mysteryobject converted to type Programmer. Type inquiry can be even done for classes we did not define.

CategoryC++


[1] Let your imagination run wild!

Copyright © 2004-2011 Anirudh Sasikumar. All rights reserved.
Last Updated: January 21, 2005 4:35 PM