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.
int i = c;
. – Pontonec
can be converted to an int here. – Eroticc = 1
does not "convert to an int". After all is said and done, you still have aC
remaining, and not an int. C++ has rules for everything. If you want it to work this way, that's whatoperator=
is for.operator=
is for assigning to an instance of a class. A conversion operator is for assigning from an instance of a class. – Hainesint
, then defineoperator int()
, and thenint d=c
will work. Those are your options. That's the only way that C++ works. – Hainesc_str()
and not overloadingconst char *
is done forstd::string
. – Laporteoperator Type()
member function. If you convert from your classA
to your classB
you can use either of those conversion function mechanisms (put into the respective correct class of those two). As in the example you want to convert from the built-inint
only the constructor solution works. – Grip