samedi 2 octobre 2021

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

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;
}

Aucun commentaire:

Enregistrer un commentaire