Recent Blog Posts

Other Content

C++ Casts

c-style cast: lets you do whatever you want. Generally good to avoid in C++. Absolutely never use when multiple inheritance or virtual inheritance is involved.

const_cast<>: lets you cast away const-ness. Think a whole lot before using!

reinterpret_cast<>: of the c++ casts, its the most like the C cast. More or less lets you do whatever you want, and you had better know what you're doing

static_cast<>: This will let you upcast and downcast, and do other sensible things. But senseless things will not compile.

dynamic_cast<>: Stuff that won't compile with static cast won't compile with dynamic_cast. Except with dynamic cast, the cast is checked at runtime to make sure its valid. (so, if B and C both extend A, and you have a pointer to an A which is really a B, and you do: dynamic_cast(myA), it will check this at runtime). If the cast is invalid at runtime, it will return NULL, or if you are casting to a reference type, it will throw an exception (std::invalid_cast_exception, i think). dynamic_cast is most like Java's cast. static_cast is second most like Java's cast, except that no runtime checking is done so its fast.

Neal: do I have to enable RTTI for dynamic cast to work?

Mike: ya

RTTI sticks a bit of stuff before the v-table which is a lot like Java's Class class pointer. dynamic_cast and type_info or type_id or whatever its called needs that. or may be its a second pointer along side the vtable pointer. I'm not 100% sure on the implementation, but thats the effect.