name3r123
name3r123

Reputation: 163

Overloading post-increment operator

MyClass MyClass::operator++(int) {
    return ++(*this);
}

That's the code I have written. I works correctly, but all tutorials say that I have to create a temporary object and return it:

MyClass MyClass::operator++(int) {
    MyClass tmp = *this;
    ++(*this);
    return tmp;
}

Please tell me which way is the best?

Upvotes: 5

Views: 1566

Answers (4)

Rob Kennedy
Rob Kennedy

Reputation: 163247

The tutorials are correct.

Your version returns the wrong value. The post-increment operator is supposed to return the previous value, not the new value. Check for yourself with a plain old int:

int x = 5;
int y = x++;
cout << x << y << endl; // prints 56, not 66.

Upvotes: 2

Yochai Timmer
Yochai Timmer

Reputation: 49221

That's due to the definition of post-increment operator.

post-increment operator: Increments AFTER the value is used.

pre-increment operator: Increments BEFORE the value is used.

So if you do it your way, the value returned from the function is the incremented one.

The tutorials increment the object itself, but return a non incremented COPY of the object.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206508

Second One! Post Increment means that the variable is incremented after the expression is evaluated.

Simple example:

int i = 10;
int j = i++;

cout<<j; //j = 10
cout<<i; // i = 11

Your First example would make j = 11, which is incorrect.

Upvotes: 5

C. K. Young
C. K. Young

Reputation: 222973

The first version is wrong, because it returns the new value. The postincrement operator is supposed to return the old value.

Upvotes: 6

Related Questions