Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading post-increment operator

Tags:

c++

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?

like image 700
name3r123 Avatar asked Jun 16 '11 16:06

name3r123


People also ask

Can post-increment operator be overloaded?

The postfix increment operator ++ can be overloaded for a class type by declaring a nonmember function operator operator++() with two arguments, the first having class type and the second having type int . Alternatively, you can declare a member function operator operator++() with one argument having type int .

What is ++ i and i ++ in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.

What will happen ++ i ++ in code?

++i will increment the value of i , and then return the incremented value. i++ will increment the value of i , but return the original value that i held before being incremented.

What is post-increment operator in C++?

2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;


3 Answers

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

like image 100
Chris Jester-Young Avatar answered Nov 16 '22 18:11

Chris Jester-Young


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.

like image 44
Alok Save Avatar answered Nov 16 '22 20:11

Alok Save


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.
like image 2
Rob Kennedy Avatar answered Nov 16 '22 18:11

Rob Kennedy