Type casts in C++, explained
As explained by my colleague, former professional C++ developer (now writes schwifty Java).
Below is a quick explanation of four basic C++ type casts. Just for the matter of shorter post,
consider each cast taking a template type T
and a parameter value v
like this: const_cast<T>(v)
.
const_cast
- removes theconst
from the type ofv
(think of castingconst char*
will producechar*
)static_cast
- C-style, unchecked explicit type casting (just like in old 90s:(int) 3.14
)reinterpret_cast
- hard low-level treating a block of memory as typeT
, no matter what resides in that memorydynamic_cast
- does the runtime checks of param type and template type