Types
Type | Area | Risk |
---|---|---|
static_cast | – Converts fundamental types – Non-const to const – Down-casts (dangerous) |
Medium |
dynamic_cast | – Down- and side-casts | Low |
const_cast | – Removes and adds const | High |
reinterpret_cast | – Converts nearly everthing – Not: const to non-const |
Very high |
C-style casts in C++ are trying the following casts in the following order:
- const_cast
- static_cast
- static_cast, then const_cast
- reinterpret_cast
- reinterpret_cast, then const_cast
Usage
Good projects should be designed that it’s not often necessary to cast types (explicit conversion).
Those few casts should be just static_cast and dynamic_cast. Use static_cast for conversions between fundamental types and dynamic_cast for down- and side-casts. If the static_cast is not possible you got an error during compile-time and if the dynamic_cast is failing you got for pointer a nullptr and for references an bad_cast exception during run-time.
Don’t use const_cast, reinterpret_cast and C-style cast. If something has been defined const its for a reason, so don’t remove it with a const_cast. Think about chages in your class structures if you really have to use reinterpret_cast. But the worst are C-style casts, they are just evil!