focusHard
focusHard

Reputation: 271

C++ operator overloading prefix/suffix

I'm learning operator overloading in C++. The original suffix ++ has the property that it has lower precedence than the assignment operator. So for example, int i=0, j=0; i=j++; cout<<i<<j will output 01. But this property seems to be lost when I overload the postfix ++.

#include<iostream>
using namespace std;

class V
{
public:
    int vec[2];
    V(int a0, int a1)
    {
        vec[0]=a0;vec[1]=a1;
    }
    V operator++(int dummy)
    {
        for(int i=0; i<2; i++)
        {
            ++vec[i];
        }
        V v(vec[0],vec[1]);
        return v;
    }
    V operator=(V other)
    {
        vec[0]=other.vec[0];
        vec[1]=other.vec[1];
        return *this;
    }
    void print()
    {
        cout << "(" << vec[0] << ", " << vec[1] << ")" << endl;
    }
};

int main(void)
{
    V v1(0,0), v2(1,1);
    v1.print();

    v1=v2++;
    v1.print();
}

outputs (0,0)(2,2) while I expected (0,0)(1,1).

Can you help me understand why it's like this, and any possibility of restoring the original property?

Upvotes: 4

Views: 2363

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126442

It prints (0,0)(2,2) because your operator ++, unlike the built-in one, returns a copy of the V object it acts upon after incrementing it, rather than before.

This is completely under your control when you overload an operator, so it is your responsibility to make it behave like the corresponding built-in operator in this respect.

This is how you could rewrite your operator to achieve that goal:

V operator++(int dummy)
{
    V v(vec[0],vec[1]); // Make a copy before incrementing: we'll return this!
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v; // Now this is *not* a copy of the incremented V object,
              // but rather a copy of the V object before incrementing!
}

Here is a live example.

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 361635

You need to make a copy of vec[0] and vec[1] before you increment them, not after. That way return v will return the original values rather than the incremented ones.

V operator++(int dummy)
{
    V v(vec[0],vec[1]);
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v;
}

Upvotes: 1

Related Questions