In C++ some types are related to each other. When two types are related, we can use an object or value of one type where an operand of the related type is expected. Two types are related if there is a conversion between them.
As an example, consider the following expression, which initializes ival
to 6:
int ival = 3.541 + 3; // the compiler might warn about loss of precision
The operands of the addition are values of two different types: 3.541
has type double
, and 3
is an int
. Rather than attempt to add values of the two different types, C++ defines a set of conversions to transform the operands to a common type. These conversions are carried out automatically without programmer intervention—and sometimes without programmer knowledge. For that reason, they are referred to as implicit conversions.
The implicit conversions among the arithmetic types are defined to preserve precision, if possible. Most often, if an expression has both integral and floatingpoint operands, the integer is converted to floating-point. In this case, 3
is converted to double
, floating-point addition is done, and the result is a double
.
The initialization happens next. In an initialization, the type of the object we are initializing dominates. The initializer is converted to the object’s type. In this case, the double
result of the addition is converted to int
and used to initialize ival
. Converting a double
to an int
truncates the double
’s value, discarding the decimal portion. In this expression, the value 6
is assigned to ival
.