C++ is
strictly typed language. If we start by saying that name "foo" means an integer variable, the compiler can and will check that every time the foo is used, it is consistently treated as integer.
At times we need to explicitly convert a value (of variable) to a different type. That is
type casting.
For example:
1 2 3 4
|
int foo = 4;
int bar = 5;
std::cout << foo / bar << '\n';
std::cout << static_cast<double>(foo) / bar << '\n';
|
0
0.8 |
Line 3 is
integer division and that discards the remainder. Since 4<5, the result is integer 0.
On line 4 we first explicitly create a (temporary unnamed) double value from the foo. We cast int to double.
There is no division operator that takes double and int, so the compiler has to choose between int/int and double/double and the latter wins.
Next, the compiler implicitly casts the bar into double.
The result of
floating point division (4.0 / 5.0) is a double value 0.8.
Casting a pointer is similar. A pointer has an address of a memory block and type information about what that memory block is supposed to contain. With a cast of the type we can claim that the memory contains something else than what the pointer's type says. However, the cast should make sense; be a feasible conversion. (Analogously, we could claim that the banana on your hand is a gun, but if you try to fire the "gun", the result will not be what firing a gun is supposed to be like. We would have "broken" the strict type consistency.)