RTTI in C++

RTTI (Run-Time Type Information) is used to obtain information about value type at run-time. In C++ it is popular to say it should be avoided, because it slows down processing and can be avoided. A popular anti-pattern that can be found inside beginner questions looks like follows:

double calcArea(Shape &shape) {
{
   if (typeid(shape) == typeid(Rectangle))
   {
     Rectange *rect = dynamic_cast<Rectangle *>(&shape);
     return rect->a * rect->b;
   } else {
   ...
   }   
}

This code hase several flaws:

  • it will not work with classes derived from Rectangle if not included explicit in this code (breakes LSP rule)
  • it uses RTTI (dynamic_cast slows down processing)
  • it forces you to change "calcArea" each time you want to add new shape (breakes OCP rule)

Better solution:

double calcArea(Shape &shape) {
{
   return shape.getArea(); // getArea is a virtual function implemented in Shape-derived classes
}

RTTI features

  • typeid: returns reference to object of class type_info describing input object, can be used to compare types of objects
  • typeid(a).name(): returns name of class of object a
  • dynamic_cast: checks if provided object can be casted to selected class, if yes - returns casted object
  • dynamic_pointer_cast (C++11): converts type of shared pointer

Not really RTTI

  • std::is_same (C++11): compare two types - during compilation
  • type_traits (C++11): compile-time checks of features of provided type
  • static_cast: cast value to another type in run-time without using RTTI (just convert)
  • static_pointer_cast (C++11): cast shared_ptr with static_cast

Presentations

See also

Share

follow