Why are C-style casts discouraged in C++?
Short answer
A C-style cast (int)x tries static_cast, then const_cast, then reinterpret_cast (and combinations) in sequence, so it can silently perform a dangerous reinterpret or strip const without you realizing.
Advertisement
AModel answer
A C-style cast (int)x tries static_cast, then const_cast, then reinterpret_cast (and combinations) in sequence, so it can silently perform a dangerous reinterpret or strip const without you realizing. The named casts express precise intent, are easy to search for, and are checked more strictly, making code safer and clearer.
int* p = (int*)someObj; // could be a hidden reinterpret_castReal-world example
A C-style cast accidentally reinterprets an unrelated pointer; a named cast would have failed to compile.
Likely follow-ups
- What sequence does a C-style cast try? | Why are named casts searchable?
Related topics