Language: EN

cpp-conversion-tipos-cast

Convert between types with Cast in C++

Type conversion (also known as coercion or casting) is an operation that allows us to transform a value from one data type to another.

This is necessary when working with different data types and we need a value to be treated as another specific type.

In C++, there are several ways to perform conversions between types, in two main categories: implicit conversions and explicit conversions.

Implicit Conversions

Implicit conversions occur automatically when the compiler can convert one data type to another without loss of significant information.

This happens when the destination type can hold all possible values of the source type without the risk of truncation.

For example, if you have a variable of type int and you want to assign its value to a variable of type long, C++ will perform the implicit conversion without needing you to specify it:

int integerNumber = 10;
long longNumber = integerNumber;

In this case, integerNumber is implicitly converted to long and assigned to longNumber.

Explicit Conversions

Explicit conversions require that the programmer indicates to the compiler that they wish to perform a type conversion.

If the conversion is not valid, it will cause a runtime error 💥

Conversion with Operator

To perform an explicit conversion in C++, we can use the casting operator

(dataType)object

Where,

  • dataType: is the target data type
  • object: is the object that you want to convert.

For example, if we have a variable of type float and we want to convert it to an int, we need to perform an explicit conversion:

float decimalNumber = 3.14f;
int integerNumber = (int)decimalNumber;

Conversion with Specific Cast

Since C++98, in addition to the classic casting operator (dataType), specific converters static_cast, dynamic_cast, and const_cast are available.

These types of casts offer greater control and safety over conversions between types, helping to avoid common errors and ensure more predictable behavior.

We will see it in the article Static_cast, Dynamic_cast, and Const_cast Converters
read more ⯈