Is there an actual difference between a const_cast and c style cast (ObjectType) ?
A const_cast
can only add or remove const
-ness (or volatile
-ness, though this is much less common).
A C-style cast can do the same as any of the "new" casts, except for a dynamic_cast
(and it can do a few things none of them can do, though it's not really relevant here).
A const_cast is more restricted and won't let you do anything other than change const-ness. That makes it safer i.e. less accident-prone.
In addition it's easier to search for.
C-style cast in C++ attempts a static cast, a reinterpret cast, a const cast, or a combination of those.
It is recommended to avoid C casts mainly because...
Same action. A C-style cast can cast away the const all the same.
The reason for const_cast is that it can serve as a searchable red flag, something to search for and carefully review/punish the guilty. The idea is that C++ is much more type-tight that C. So deliberate violations of the type system (such as violating const correctness), if not impossible, are easy to spot.
Making such violations of the type safety completely impossible would break too much backwards compatibility.
const_cast
can modify only the const-ness (or volatile-ness) of the argument, not it's basic type. So
const T *tc = f();
volatile T *tv = g();
U *ua = const_cast<U*>(tc); //error
U *ub = const_cast<U*>(tv); //error
U *ub = (U*)(tc); //okay
U *ub = (U*)(tv); //okay
So c-style cast modifies cv-qualified T*
to U*
without any problem.
A const_cast
conveys specific information about the intent behind the cast that a C cast cannot.
If you accidentally try to use a const_cast
for purposes other than adding or removing const
or volatile
, the compiler will help you with an error message.
Also, const_cast
is searchable, unlike a C-style cast.