The evil C-style cast will do just about any conversion that's remotely possible. By using that, you give up any hope of the type system catching mistakes in your code.
The C++ casts restrict the types of conversions that are possible, reducing the scope for accidentally casting to the wrong thing.
For example, this cast will compile, but give some kind of undefined behaviour if you try to use the pointer:
double * bad = (double*)ptr;
while this cast will fail to compile, since const_cast
can't do type conversions:
double * less_bad = const_cast<double*>(ptr);
The casts work (more or less) as follows:
static_cast
allows you to undo "safe" conversions; for example, converting a pointer to a base class to a pointer to a derived class, or void*
to a typed pointer. It doesn't allow conversions that don't make sense under the type system.
reinterpret_cast
allows wonkier conversions, such as converting pointers to integers or unrelated pointer types. Use it with care, if you need abandon the type system to do something funky.
const_cast
allows you to remove const
and volatile
qualifiers, while not allowing type conversions.
dynamic_cast
allows conversion between pointers or references to polymorphic types, with a run-time check that the conversion is valid. This is the only "safe" cast, as it cannot give a wrongly-typed result.
- The evil C cast allows anything that
static_cast
, reinterpret_cast
and const_cast
can do, and more besides. The syntax is hard to spot, or to search for, so use this if you want to hide the true horror of your code and drive maintenance programmers into insanity.