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 conversions between types, divided 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 loss of significant information.
This happens when the destination type can contain 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 having 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 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 operator
To perform an explicit conversion in C++, we can use the casting operator
(dataType)object
- dataType: is the destination data type
- object: 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;
Conversion with specific cast
Starting from C++98, in addition to the classic casting operator (dataType)
, the specific converters static_cast
, dynamic_cast
, and const_cast
are available.
These types of casts provide greater control and safety over type conversions, helping to avoid common errors and ensuring more predictable behavior.
We will see it in the article Static_cast, Dynamic_cast, and Const_cast Converters
read more