This function definition:
operator int&() { return value; }
Allows a conversion from your class Foo
to a reference to int.
This line:
p++;
Cannot increment p
as type Foo
as the class does not have operator++
implemented. However it is able to convert p to a reference to int
via a call to operator int&()
which returns a reference to value
within the particular instance of Foo
. The reference to value
is of type int
which can be incremented using ++
. So the code then increments value
in-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:
class Foo
{
public:
Foo() : m_value(0)
{
}
int getCopy() { return m_value; }
int& getRef() { return m_value; }
private:
int m_value;
};
int main()
{
Foo f;
// Works
f.getRef()++;
// Does not work on g++ with 'error: lvalue required as increment operand`
f.getCopy()++;
}
The reason you cannot do an increment when the conversion operator returns int
rather than int&
is that the increment operation requires an lvalue, i.e. something that can be the target of an assignment. See here for more detail.