A lot of code deals with transforming data from one data type to another. There are many reasons for doing this. The different sizes of integer numbers and changing their sign is one issue. In the past, casting was easy and error-prone. C++ has different ways to deal with casting data types. The full list of methods involves:

  • static_cast<T> is for related data. The checks perform at compile time, not at run-time.
  • dynamic_cast<T> is useful for pointers. It checks the data type at run-time and ensures that unsafe downcasts are avoided. Catching errors usually results in an exception.
  • const_cast<T> does not change the data type. It just tells the compiler not to expect any write operations on the data. This is useful for optimisation choices implemented by the compiler.
  • reinterpret_cast<T> is the worst option for converting/casting data. The compiler will enforce the new data type. So this should only be an option if you know what you are doing.
  • std::move is new in C++11/C++14. It doesn’t change the data type, but the location of the data. You can move values and instances with it. The main reason for moving things is to protect them from unintended modification.

While you can still use the old-fashioned C-style cast operation, you should never do this in C++. The list of options document more clearly what you intend to do in your code. For more complex operations, it is recommended to create a method for performing the transformation. This method can also enforce range checks or other tests before converting data. There is a blog article that illustrates the conversion methods by using Han Solo from Star Wars.

Using constants and constant expressions is something you absolutely should adopt for your coding style. Marking data storage as read-only allows the compiler to create faster code. In addition, you will get errors when other parts of your code modifies data that should not be changed.