I understand that we can apply increment and decrement on intrinsic data types such as:
int a;
a++;
a--;
…etc.
However, in the following codes, if I omit the & in the line operator int& ( ) { return value; }, I will get a compile error. Please explain how and why using & makes the increment possible here:
#include <iostream>
class Foo {
public:
int value;
operator int& ( ) { return value; }
};
int main ( ) {
Foo p;
p.value = 10;
p++;
std::cout << p << std::endl;
std::cin.get ( );
return 0;
}
This function definition:
Allows a conversion from your class
Footo a reference to int.This line:
Cannot increment
pas typeFooas the class does not haveoperator++implemented. However it is able to convert p to a reference tointvia a call tooperator int&()which returns a reference tovaluewithin the particular instance ofFoo. The reference tovalueis of typeintwhich can be incremented using++. So the code then incrementsvaluein-place.As to the distinction between returning an in and a reference to int, the following code shows the behaviour you mention is not distinct to the conversion oeprator:
The reason you cannot do an increment when the conversion operator returns
intrather thanint&is that the increment operation requires an lvalue, i.e. something that can be the target of an assignment. See here for more detail.