Additionally, In case of dynamic_casting it throws and bad_cast exception. |
C-style cast does not perform run time polymorphic conversion, that is, it never does
dynamic_cast
, because C language doesn't use polymorphism.
Few examples what happesn:
1. When you use C style cast on base type and attempt to cast it to unrelated derived type or vice versa, what happens behind the scene is
reinterpret_cast
, and using such returned pointer is
undefined behavior and not std::bad_cast
as you are expecting. it succeeds where
dynamic_cast
would fail!
2. Another example, when you use C style cast on base type and attempt to cast it to derived type, what happens behind the scene is
static_cast
, and using such returned pointer is again
undefined behavior and not std::bad_cast
as you are expecting.
3. However if you cast from derived type to base type then again
static_cast
is performed, and if needed to cast const away then
const_cast
is performed too, This last case is not necesarily undefined behavior, unless your derived type has multiple bases, with common abstract base, so again C style cast is bad here too, becuase
dynamic_cast
would perform
side cast in this case while C style cast would not!
In all cases above,
const_cast
is automatically performed if needed!