Casting is a conversion process wherein data can be changed from one type to another. C++ has two types of conversions:
- Implicit conversion: Conversions are performed automatically by the compiler without the programmer’s intervention.
1 | int iVariable = 10; |
- Explicit conversion: Conversions are performed only when explicitly specified by the programmer.
1 | int iVariable = 20; |
In C++, there are four types of casting operators.
static_cast
const_cast
reinterpret_cast
dynamic_cast
In this article we will only be looking into the first three casting operators as dynamic_cast is very different and is almost exclusively used for handling polymorphism only which we will not be addressing in this article.
static_cast
Format:
static_cast<type>(expression);
1 | float fVariable = static_cast<float>(iVariable); /*This statement converts iVariable which is of type int to float. */ |
By glancing at the line of code above, you will immediately determine the purpose of the cast as it is very explicit. The static_cast tells the compiler to attempt to convert between two different data types. It will convert between built-in types, even when there is a loss of precision. In addition, the static_cast operator can also convert between related pointer types.
1 | int* pToInt = &iVariable; |
const_cast
Format:
1 | const_cast<type>(expression); |
1 | void aFunction(int* a) |
Probably one of the most least used cast, the const_cast does not cast between different types. Instead it changes the “const-ness” of the expression. It can make something const what was not const before, or it can make something volatile/changeable by getting rid of the const. Generally speaking, you will not want to utilise this particular cast in your programs. If you find yourself using this cast, you should stop and rethink your design.
reinterpret_cast
Format:
1 | reinterpret_cast<type>(expression); |
Arguably one of the most powerful cast, the reinterpret_cast can convert from any built-in type to any other, and from any pointer type to another pointer type. However, it cannot strip a variable’s const-ness or volatile-ness. It can however convert between built in data types and pointers without any regard to type safety or const-ness. This particular cast operator should be used only when absolutely necessary.