C++ Explicit type conversions Implicit conversion


static_cast can perform any implicit conversion. This use of static_cast can occasionally be useful, such as in the following examples:

  • When passing arguments to an ellipsis, the "expected" argument type is not statically known, so no implicit conversion will occur.

    const double x = 3.14;
    printf("%d\n", static_cast<int>(x)); // prints 3
    // printf("%d\n", x); // undefined behaviour; printf is expecting an int here
    // alternative:
    // const int y = x; printf("%d\n", y);

    Without the explicit type conversion, a double object would be passed to the ellipsis, and undefined behaviour would occur.

  • A derived class assignment operator can call a base class assignment operator like so:

    struct Base { /* ... */ };
    struct Derived : Base {
        Derived& operator=(const Derived& other) {
            static_cast<Base&>(*this) = other;
            // alternative:
            // Base& this_base_ref = *this; this_base_ref = other;