- [Man] The typecast operator converts a value
from one type to another compatible type.
Here's working dot cpp
from chapter four of the exercise files.
For many purposes the conversion of one type
to another may happen automatically.
And this is called an implicit conversion.
And so if I come in here and I declare an integer,
and then I declare another longer integer,
say long long int,
and then I assign the value X to Y.
So I'm assigning a smaller integer
to a larger integer.
And I'll go ahead and print them both out.
When I build this and run it,
you'll see it works as expected.
X is five and Y is five.
And so what's happened here
is what's called an implicit conversion.
Because X is smaller than Y,
it's a regular integer,
instead of long long integer,
it takes up less space.
There's no danger of losing any data
when I promote it to a long long int.
But if I try to do it the other way around.
And when I go to build,
you'll notice I get a warning,
implicit conversion loses integer precision.
And that's because X is a lower precision than Y.
And so there's a possibility of losing data,
when I try to convert the Y to X.
When I convert the X to Y,
the int to a long long int,
that's considered a promotion.
The long long int has more space,
and so it can easily hold
the value of regular integer.
The reverse is not true.
And so this will not work implicitly.
Instead, I need to use an explicit cast.
And this is the cast operator.
It's a type in a pair of parentheses,
just like that.
And it's a unary operator
and so it operates on the operand to its right.
And so this converts that long long int,
to a regular int and it just tells the compiler.
"Look, I know what I'm doing here,
this is what I intend to do.
It's entirely intentional.
And if I lose any data,
it's my fault, not yours."
And so now when I build and run this,
you see it works exactly as expected.
So the cast operator,
is an explicit conversion,
whereas without the cast
it's an implicit conversion.
Now the cast operator
still won't work if the types are incompatible.
So if I come in here,
and I declare a string,
and then I try to assign that to X.
And try to build that you see
this is not a warning this is now an error.
And even if I come in here
and try to cast it with an explicit conversion,
when I try to build says,
cast from pointer to smaller type int loses information.
This is an error, not a warning.
So the typecast operator
converts a value from one type
to another compatible type.
Some type conversions may happen automatically,
like smaller to larger integer types.
Others require the cast operator
and type conversions may only be performed
on compatible types.