c++c++11explicit-constructor

Prevent undesired conversion in constructor


According to here, explicit:

Specifies constructors and conversion operators (since C++11) that don't allow implicit conversions or copy-initialization.

Thus, are these two techniques identical?

struct Z {
        // ...
        Z(long long);     // can initialize with a long long
        Z(long) = delete; // but not anything smaller
};

struct Z {
        // ...
        explicit Z(long long);     // can initialize ONLY with a long long
};

Solution

  • They're not identical.

    Z z = 1LL;
    

    The above works with the non-explicit version, but not with the explicit version.

    Declaring constructor of Z explicit doesn't prevent conversion of the constructor argument from another type. It prevents the conversion from the argument to Z without calling the constructor explicitly.

    Below is an example of explicit constructor call.

    Z z = Z(1LL);