Home > database >  What value explicit constructor brings when arguments passed are custom type?
What value explicit constructor brings when arguments passed are custom type?

Time:10-03

I understand the value of keyword explicit when used in cases where there is a chance of creating ambiguity, like the examples I am seeing here and here.

Which I understand as prevents implicit conversion of basic types to object type, and this makes sense.

struct point {explicit point(int x, int y = 0);
};
point p2 = 10; // Error: would be OK without explicit

What I want to understand is what value explicit brings when I am using custom datatypes as constructor argument?

struct X {X(int x);}; // a sample custom datatype I am referring to.

struct pointA { pointA(X x);}; // here this looks to me same as 
    
struct pointB {explicit pointB(X x);}; // like here this 
    
int main() {

    pointA pa = 10; // fails as expected
    
    return 0;
}

CodePudding user response:

The point of explicit has nothing to do with the parameter list, it has to do with the type being constructed, especially if there are side-effects. For example, consider std::ofstream.

void foo(std::ofstream out_file);
// ...
foo("some_file.txt");

Without explicit, this will attempt to open some_file.txt and overwrite its contents. Maybe this is what you want, but it's a pretty big side-effect that's not obvious at the calling point. However, consider what we'd have to do since the relevant std::ofstream constructor is explicit.

foo(std::ofstream("some_file.txt"));

It's far more clear, and the caller isn't surprised (or at least shouldn't be).

Whether the type being constructed is built-in, from a third-party library, or something you wrote yourself: it's irrelevant. explicit is useful anytime you don't want a type to be constructed without somebody being very explicit (hence the keyword) that's their intention.

  • Related