C / C++ - Type Casting
Implicit conversion
implicit conversion:
int i = 42;
double d = i; // Implicit conversion from int to double
C++-style Casting
static_cast
performs no runtime checks. use it in cases like convertingfloat
toint
,char
toint
, etc. Also used in CRTP.dynamic_cast
: used for handling polymorphism. Only used used in inheritence when casting from base class to derived class.const_cast
: can be used to remove or addconst
to a variable.reinterpret_cast
: used for reinterpreting bit patterns and is extremely low level, primarily for things like turning a raw data bit stream into actual data or storing data in the low bits of an aligned pointer.
Cast to enum
auto foo_enum = static_cast<Foo>(foo_number);
Prevent implicit conversion
The explicit
keyword can be applied to a constructor or a conversion operator, to ensure that it can only be used when the destination type is explicit at the point of use, e.g., with a cast.
Type conversion operators, and constructors that are callable with a single argument, must be marked explicit
in the class definition.
C-style Casting
Syntax: (new_type)expression
For example: (int)3.5
.
A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast
. More powerful as it combines all of const_cast
, static_cast
and reinterpret_cast
, but it's also unsafe.