Casting operators in C++

  • static_cast<>
  • const_cast<>
  • dynamic_cast<>
  • reinterpret_cast<>
  • C-style casts

static_cast<>
Is for widening numeric conversions (e.g., int to float), converting between pointer types and void*.
Can also be used to call explicit (or implicit) conversion functions.
Can cast around the hierarchy but it isn’t checked.

const_cast<>
Add or remove const to a variable.
Not so important because of mutable.
Can be used to call const-overloaded member functions.
Can also add or remove volatile

dynamic_cast<>
For casting around hierarchies.
Will return nullptr on failure for a pointer, or throw std::bad_cast for references.
Can cast sideways and up other hierarchies
Doesn’t work if you have a diamond and haven’t used virtual inheritance
Only works for public inheritance

reinterpret_cast<>
Will convert anything into anything.
Use to cast a pointer to or from an opaque type, or to cast a blob of memory to a POD type
Is reversible unless you cast to a type with less storage space

C-style casts
T(object) or (T)object
This is the same thing as a "function-style cast"
Perform the new casts in order:

  1. const_cast
  2. static_cast
  3. static_cast then const_cast
  4. reinterpret_cast
  5. reinterpret_cast then const_cast

Note that dynamic_cast is not in this list – you can cast around the hierarchy with C-style casts, but it isn’t checked