Search code examples
c++rtti

Why should I use RTTI?


I hear a lot that RTTI can be avoided by using good virtual functions...since RTTI is clunky and slow, why should I use it? Are there any situations where I should use RTTI instead of virtual accessor functions?


Solution

  • RTTI can be used to solve the double dispatch problem (a function that behaves virtually based off the dynamic type of two objects).

    RTTI gives you automatic access to the class inheritance graph of types with virtual methods.

    Like some other language features, if you only want a restricted subset of its features (if you are ok with a centralized list, or single implementation inheritance, or even single binary, or lack of availability early/late in execution, etc) you can sometimes implement a more efficient, restricted version.

    In addition, often double dispatch can be refactored into orthogonal single dispatches. And even if RTTI allows multiple dispatch, the code remains messy and difficult to maintain and RTTI can be a non trivial cost (note that compilers are much better at it now). So often a simpler, seemingly less efficient single dispatch solution ends up being a better idea anyhow.

    RTTI can also be used in despirwtion when you need dynamic dispatch, but have no access to the ability to add new virtual methods for whatever reason.

    Tightly coupled classes that expose pure interfaces but need to work with each others guts can use RTTI when paranoid about the dangers of blind static_cast as well.