2

In OOP concept, is the RTTI (Run Time Type Information) is also used for static casting or it is used only for dynamic casting?

If it is specific for dynamic casting then justify your answer and also please explain why no RTTI for static_casting.

Whats the point in using RTTI for downcasting?

Mat
  • 202,337
  • 40
  • 393
  • 406
NEO
  • 149
  • 1
  • 14

3 Answers3

5

A static cast is a compile-time construct, whereas RTTI is a run-time phenomenon. This means that no, RTTI is not used for static_cast.

I suggest you read this thread as it has a lot of great info.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Use `static_cast` when you *know* the run-time type, `dynamic_cast` otherwise. You don't really have a choice. – spraff Sep 13 '11 at 16:02
1

static_cast does no run-time checking, so presumably it requires no RTTI to be present. (Of course, this is implementation-dependent.)

dynamic_cast does do a run-time check (and therefore requires some form of RTTI under-the-hood), which gives you a chance to deal with an incorrect cast!

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • **Presumably**? Is it not **Guaranteed** to be a compile time phenomenon? – Alok Save Sep 13 '11 at 16:00
  • @Als No, although that is clearly the intent. Never the less, lying to the compiler in a `static_cast` is undefined behavior, and anything the compiler does, including causing an immediate crash, is legal. – James Kanze Sep 13 '11 at 16:14
  • @James: No I did not mean, lying to the compiler in `static_cast`, but in any case doing so should just result in an compiler error rather than an runtime UB? Also, my real Q was, `static_cast` is guaranteed to work with only compile time information and not use any runtime information at all? – Alok Save Sep 13 '11 at 18:06
  • 1
    @Als No. With `static_cast`, the compiler trusts you; it isn't required to do any runtime checking, and the intent is that it not do such checking. If the `static_cast` is a lie---if the object actually pointed to doesn't have the type claimed---then the results are undefined behavior. (I'm only talking about pointer conversions here. Things like `static_cast` of an `int` are a different matter.) – James Kanze Sep 14 '11 at 07:26
1

Here's the trick, if you have some classes like A,B,C,D,E, and they have a common baseclass Base, then a downcast from Base needs to choose correct class. The casting only works if the original object was created to have the same class. In the example with 5 derived classes and one Base class, there is 1:5 chance of getting it right. Which is not very good, and programmers often choose it wrong. static_cast cannot detect the problem at all and wrong choice of the type in static_cast results in crashes. dynamic_cast can detect it, but only in runtime, i.e. dynamic_cast can also fail and return NULL or throw an exception. RTTI is needed so that dynamic_cast can fail properly.

tp1
  • 1,197
  • 10
  • 17