Angelo
Angelo

Reputation: 344

In C++, why do I get different results using or not reference as result value?

class point
{
private:
    double x,y;
public:
    point(double x=0.0, double y=0.0)
    {
        this->x=x;
        this->y=y;
    }

    point operator++()
    {
        this->x=this->x+1.0;
        this->y=this->y+1.0;
        return *this;
    }

    point& operator++(int)
    {
        point p=point(this->x, this->y);
        ++(*this);
        return p;

    }

    ostream& operator<< (ostream& o)
    {
        o << "X: " << this->x << endl << "Y: " << this->y;
        return o;
    }

    friend ostream& operator<< (ostream& o,point p)
    {
        o << "X: " << p.x << endl << "Y: " << p.y;
        return o;
    }
};


int main()
{
  point p = point();
  p++ << cout << endl; // first output
  cout << p++ << endl;// second output
}

I don't understand why the first output is incorrect (X: 6.95333e-310 Y: 6.95322e-310), while the second one is correct (X: 1 Y: 1).

And why this problem is solved by removing & at the end of the return value of the post-increment operator?

Upvotes: 0

Views: 144

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275740

When you return a reference to a local variable, using that reference is undefined behavior.

Your compiler should be warning you about it. If it is not, increase your compiler warning level, and pay attention to the warnings.

point& operator++()
point operator++(int)

are the correct return values.

The rest of your code appears fine.

I would remove using namespace std;, and change the implementation of ++ to be:

    ++x;
    ++y;
    return *this;

Upvotes: 4

Related Questions