Type Casts

You can specify an explicit conversion by using a type cast, like this:

int numerator = 5, denominator = 7;
double bad = numerator / denominator;   // OOPS!!! now 0
double good = static_cast<double>(numerator) / denominator;
  1. numerator and denominator are both integers
  2. bad is a double, but the calculation uses int, so bad ends up with 0.0.
  3. static_cast creates a temporary, anonymous double to "stand in" for numerator during the calculation, so floating-point (true) division is performed instead of integer division.

There are four named casts. We'll meet others later. Bjarne Stroustrup, (the inventor of C++) has listed several reasons why you should use these new-style casts on his C++ FAQ.