C++ Type Conversion and Casting

Type conversion changes a value from one type to another. C++ has automatic (implicit) and manual (explicit) conversion.

Implicit conversion

#include <iostream>

int main() {
    int a = 7, b = 2;
    std::cout << a / b << '\n';             // integer division: 3
    double d = a;                            // int to double, safe
    std::cout << d << '\n';
    int x = 3.9;                             // double to int: the decimal part is cut
    std::cout << x << '\n';
}
Output

3
7
3

Explicit conversion with static_cast

In C++ use static_cast. It is clear and easy to search.

#include <iostream>

int main() {
    int a = 7, b = 2;
    std::cout << static_cast<double>(a) / b << '\n';
    std::cout << static_cast<int>(9.78) << '\n';
    char c = static_cast<char>(66);
    std::cout << c << '\n';
}
Output

3.5
9
B

The four C++ casts

CastUse
static_castNormal safe conversions (numbers, related pointers)
dynamic_castSafe downcast in a class hierarchy, checked at run time
const_castRemove or add const (rarely needed)
reinterpret_castLow level re-reading of bits. Dangerous

The old C style cast (int)x can do any of these without telling you, so avoid it in C++.

Strings and numbers

#include <iostream>
#include <string>

int main() {
    int n = std::stoi("42");
    double d = std::stod("3.5");
    std::string s = std::to_string(100) + " items";
    std::cout << n + 1 << " " << d * 2 << " " << s << '\n';

    try {
        std::stoi("abc");
    } catch (const std::invalid_argument& e) {
        std::cout << "Not a number\n";
    }
}
Output

43 7 100 items
Not a number

Narrowing and overflow

#include <iostream>

int main() {
    long long big = 3'000'000'000;
    int small = static_cast<int>(big);       // does not fit: the value is wrong
    std::cout << small << '\n';
    std::cout << static_cast<long long>(1e10) << '\n';
}
Output

-1294967296
10000000000

Note: Convert only when you must, and use static_cast so everybody can see it. Next: C++ Operators.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.