0

What is the use of run time type identification in C++? I know how it is used and what facilities it provides but what was the motivation behind introducing RTTI in C++? Can anyone give a small example where RTTI has to be used?

username_4567
  • 4,737
  • 12
  • 56
  • 92

3 Answers3

1

Here is an example: Sometimes you would want to (though you should avoid to) downcast polymorphic objects. In many cases, you do not know at compile time whether this cast will be valid every time you do it:

struct Base { virtual ~Base() {} };
struct A : Base {};
struct B : Base {};

void foo(Base * base)
{
    A * a = dynamic_cast<A *>(base); // RTTI magic here!
    if(a != nullptr)
    {
        // do something with a
    }
}

Notice that RTTI comes at the cost of runtime checks and thus performance loss, but you probably already know that if you are familiar with the concept.

nikolas
  • 8,707
  • 9
  • 50
  • 70
1

You can use it when checking post-condtions:

class Clonable
{
    virtual Clonable* doClone() const = 0;
public:
    Clonable* clone() const
    {
        Clonable* results = doClone();
        assert( typeid(*results) == typeid(*this) );
        return results;
    }
};

It can also be used as an index into a map of factory functions: in C++11, you have std::type_index with which you can wrap it; in earlier versions, you wrote your own:

std::map<std::type_index, Base* (*)()> factoryMap;

The fact that the output of std::type_info::name() isn't specified, however, limits its utility much more that one would like.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

boost::any is a good example, it can hold different types (See: http://www.boost.org/doc/libs/1_54_0/doc/html/any.html and the source code at http://www.boost.org/doc/libs/1_54_0/boost/any.hpp)

  • Note that while RTTI is used in Boost.Any it is not technically necessary, and there all fallback solutions if RTTI is not available. – nikolas Sep 03 '13 at 10:46
  • @nijansen The any_cast requires RTTI to be safe. –  Sep 03 '13 at 10:56