C++: Type Conversion Operators

Type Conversion Operators

In this C+ tutorial, we cover type conversion. Many of the type conversions that happen in C++ occur without the programmer specifying any desire to convert the data type. These conversions are performed by the compiler and are called implicit type conversions. When an arithmetic expression contains multiple data types, the compiler converts all data types to the one with the greatest range, typically a double. Unfortunately, this may not always be the desired result.

When we want to make certain of our conversion or specify a conversion that differs from the compiler default, we need to use an explicit type conversion. To create a type conversion, we put the target type in parentheses before the variable to be converted, like this: (int)cCharVariable.

In the C++ literature, you will often see explicit type conversion referred to as type casting. However, I am reserving the word casting to pointer type conversion because there is an important distinction to be made: I use type conversion to indicate that a new version of the data is created and type casting to mean that we change the way the data interpreted. In later lessons, we will make the notion of type casting more concrete.

There are two different ways to perform a type conversion: we can use the conversion notion that we used above or we can use the constructor notion. The constructor notion for the previous conversion looks like this: int(cCharVariable). The notation is very similar in both cases, and both operations are equivalent for the fundamental data types. When we get into developing our own data types, however, type conversions and constructors will be distinct operations.

When converting from one type to another, some unexpected results can occur. Conversions from a double to an integer type and conversion to a bool are probably the least intuitive. The remaining conversions should be relatively obvious as long the conversion remains in the range of the target type. Otherwise, you may lose precision (converting a double to a float) or end up with a strange result.