C++ Explicit type conversions C-style casting


Example

C-Style casting can be considered 'Best effort' casting and is named so as it is the only cast which could be used in C. The syntax for this cast is (NewType)variable.

Whenever this cast is used, it uses one of the following c++ casts (in order):

  • const_cast<NewType>(variable)
  • static_cast<NewType>(variable)
  • const_cast<NewType>(static_cast<const NewType>(variable))
  • reinterpret_cast<const NewType>(variable)
  • const_cast<NewType>(reinterpret_cast<const NewType>(variable))

Functional casting is very similar, though as a few restrictions as the result of its syntax: NewType(expression). As a result, only types without spaces can be cast to.

It's better to use new c++ cast, because s more readable and can be spotted easily anywhere inside a C++ source code and errors will be detected in compile-time, instead in run-time.

As this cast can result in unintended reinterpret_cast, it is often considered dangerous.