0

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;
}
reuben
  • 3,360
  • 23
  • 28
Zzz Zz
  • 113
  • 1
  • 6

1 Answers1

2

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.

Community
  • 1
  • 1
Alex Wilson
  • 6,690
  • 27
  • 44
  • Isn't this line " operator int ( ) { return value; } " converts class Foo to an int any way? although not a reference to int, but int nevertheless, so the p++ should work, but it is not. – Zzz Zz Jul 07 '12 at 20:02