static_cast
static_cast
is the first cast you should attempt to use. It converts between types using both implicit and user-defined conversions.
const_cast
const_cast
can be used to remove or add const
to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast
)
dynamic_cast
dynamic_cast
is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type
It will always fail to travel through protected
or private
inheritance.
reinterpret_cast
reinterpret_cast
is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int
, or all sorts of other nasty things.