I learned that we could provide conversion operators for our classes in C++. So I expected that for the following program, c=1;
would've used the conversion operator int()
. But to my surprise; that doesn't happen and we get a compiler error saying that
error: no match for 'operator=' (operand types are 'C' and 'int')
.
So I want to know why isn't the conversion operator used here.
struct C {
explicit C(int);
operator int&();
};
int main() {
C c({});
c = 1; //this gives error. Why the conversion operator int&() is not used here?
}
Note that I know that I can solve the error if I just remove the explicit
keyword from the constructor. But my question is about why the conversion operator is not used.
I thought that since we have a conversion operator for our class, the class object can be converted to an int
so that it can be assigned to.