There are three operators, dynamic_cast, const_cast and static_cast.
You should use them more in C++.
Unrestricted explicit type-casting allows to convert any pointer into any
other pointer type, independently of the types they point to. (syntax and
compiling is right, but cause run-time error). In order to overcome this
problem, in C++ langauge, we introduce c++ cast operator, see below
section.
You don’t need any cast operator when you change any type pointer to
void*, But when you want to use dereference void pointer , you’d
better use static_cast to change it back to a certain type pointer.
static_cast<type-name> expression will be valid only if type-name can be
converted implicitly to the same type that expression has. It will stop you
from change a bird class to an apple class which are two totally
unrelated classes. Even change int to double, encourage you to use
static_cast<double>(i). it also can help you to find cast easily in you source
code by search "static_cast".
Changing the value of an const object through const_cast pointers leads to
"undefined behavior". Most often you can. But for const static data – the
compiler may put such variables in a read-only region, the program will
crash if you try to modify it.
Using const_cast is not good design. Sometimes for a const member
function, you have to use const_cast to change this pointer to modify a
class member. If compiler support, always use "mutable" keyword. Only use
const_cast if your compiler doesn’t support mutable
Sometimes, For some legacy functions, You have a const object you want to
pass to a function taking a non-const parameter, and you know the
parameter won’t be modified inside the function. The second condition is
important, because it is always safe to cast away the constness of an object
that will only be read, not written.
dynamic_cast should only be used down-cast public inherited relationship.
Not for private or protected inherited relationship
A child pointer can be assigned to base pointer directly. dynamic_cast
use to down-cast a base pointer to child pointer. dynamic_cast
assure that down cast is valid. Because you can always safely assign
child pointer to base pointer in C++. (That is how polymorphic
implement.)
If a class doesn’t have virtual function, you can’t use dynamic_cast on this
object.
dynamic_cast can also used in reference type. When cast fail, it will not
return nullptr, (because it’s reference), just throw a bad_cast exception.
About dynamic_cast, "exceptional C++" item 44 give a good question and
answer.
reinterpret_cast converts any pointer type to any other pointer type, even
of unrelated classes. The operation result is a simple binary copy of the
value from one pointer to the other. All pointer conversions are allowed:
neither the content pointed nor the pointer type itself is checked. It can also
cast pointers to or from integer types. DON’T USE IT UNLESS YOUARE IN THE CORNER.