-1
class Point{
private:
    int xpos, ypos;
public:
    Point(int x=0, int y=0) : xpos(x), ypos(y) { }
    void showPosition() const {
        cout<<"["<<xpos<<", "<<ypos<<"]"<<endl;
    } 
    Point& operator++(){  //Point operator++()
        xpos+=1;
        ypos+=1;
        return *this;
    }
};

For operator++() I know Point& is the right return type, but I don't get why Point return type would not also work.

    Point operator++(){ 
        xpos+=1;
        ypos+=1;
        return *this;
    }

when I use this to perform

Point pos(1,3);
++(++pos);

I get

[2,4]

not

[3,5] //which is what I should be getting.

I think operator++() without the reference should still give the same result, as it would implicitly call its copy constructor, so albeit slower, I think it should give the same result.

Ji Lam
  • 23
  • 3
  • I don't understand your confusion. You obviously know that a copy of `pos` is returned by the first operation, so why do you think invoking `pos.showPosition()` afterwards is going to show the result of both operations? – Lightness Races in Orbit Jan 08 '15 at 17:40

2 Answers2

2

When ++ returns a copy, then the second ++ in ++(++pos) calls operator++ on the copy returned by the first ++, not on the original pos. Thus the original pos is only incremented once.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0
Point& operator++()

should return by reference to non-const so as to let us do ,

Point p;
++++p;

Had it returned Point, you would be trying to modify the temporary which is not the behavior you want.

ravi
  • 10,994
  • 1
  • 18
  • 36