Explicit conversion informs compiler about the intended conversion so it does not emit warning while compiling. There are some instances when we require to convert data type explicitly as shown below.
int a {25};
int b {4};
double result = a / b;We should expect the result be 6.25 but it will be 6 as it is integer division. We require to convert one of the operand to double to do floating point division.
double result = static_cast<double>(a) / b;Type Casting Methods
We can use static_cast, C-style casting, etc. to explicit convert types. There are other casting operators as well such as dynamic_cast , const_cast and reinterpret_cast. const_cast and reinterpet_cast are mostly avoided.
We already have seen using static_cast. Let’s see C-style casting:
int value = (int)5.444;
int value = int(5.444);Later is C-style alternative syntax that C++ provides.
It is advisable to use static_cast over C-style cast because C-style uses combination of other typecasting operators that may be dangerous to use(?).