cpp-conversion-tipos-cast

Convert between types with Cast in C++

  • 2 min

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 we work with different data types and need a value to be treated as another specific type.

In C++, there are several ways to perform type conversions, falling into 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 significant loss of information.

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

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

int integerNumber = 10;
long longNumber = integerNumber;
Copied!

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

Explicit Conversions

Explicit conversions require the programmer to indicate to the compiler that they want to perform a type conversion.

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

Conversion with Cast Operator

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

(dataType)object
Copied!
  • tipoDato: is the target data type
  • objeto: is the object to be converted.

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

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

Conversion with Specific Cast

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

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

If you want to know more, check out this entry