struct Foo {
int val;
Foo() : val(-1) {}
explicit Foo(int val_) : val(val_) {}
Foo& operator=(int val_) { val = val_; return *this; }
operator int () const { return val; }
};
int main()
{
Foo foo = 1; // error
Foo foo2;
foo2 = 2; // works fine
return 0;
}
error: conversion from 'int' to non-scalar type 'Foo' requested
Foo foo = 1;
The code should be self-explanatory. I would like to understand why the direct assignment is illegal when a suitable assignment operator has been defined.
>Solution :
Unlike foo2 = 2;, Foo foo = 1; is not assignment, but initialization. Only constructors would be considered (to construct foo). The appropriate constructor Foo::Foo(int) is marked as explicit then can’t be used in copy initialization like Foo foo = 1;.
If you make Foo::Foo(int) non-explicit then the code would work; direct initialization (which considers explicit constructor) like Foo foo(1); works too.