C++ Casting

I created a table that has lots of useful information about c++ casts.

dynamic_cast
  1. Only can be used with pointers and references.
  2. Throws bad_cast if reference can’t be cast, returns null if pointer can’t be cast.
  3. Performs runtime checking.
  4. Makes sure cast is valid & results in a complete object.
  5. Down casts are not valid (base to derived) UNLESS base is polymorphic, gives compilation error.
  6. Up casts are ALWAYS valid (casting to base).
  7. Compilers must have RTTI turned on.
  8. Can cast any pointer type to void*.
static_cast
  1. Does not perform runtime checking. (compile time only)
  2. Makes sure objects are related using hierarchy tree.
  3. Up & down casts are valid.
reinterpret_cast
  1. Just copies the address over with pointers.
  2. No checking at all.
  3. Same as C-Style.
const_cast
  1. Used to remove or set constness.

Leave a Reply

You must be logged in to post a comment.