Casting

Sometimes we want to change the data type of an object—this is called casting. There are several different types of casts in C++. We’ll look at static_cast, which is interpreted at compile time.

Here’s an example:

Listing 65 cast_example.cpp
#include <iostream>

int main() {

    int a{1};
    int b{2};

    auto c = a / b;
    auto d = static_cast<double>(a) / b;

    std::cout << c << " " << d << std::endl;

}

We use static_cast<double> to promote an int to a double before doing the division.

Note

Older C-style casts still work. These take the form:

int x{1};
double y = (double) x;

but these are not recommended, as the compiler can’t always check if the conversion is allowed.