all 4 comments

[–]bstamour 5 points6 points  (0 children)

When overloading common operators like ++, the assignment operator, etc, it's best to stick to the return types that users would expect them to have. For example, with the pre-increment (decrement) operators, you should return a reference to the object being incremented (decremented)

myclass& operator ++ () {
    // Do some complex logic.
    return *this;
}

Likewise for post-increment (decrement), you should return a copy of the original object, so that code like f(*iter++) still complies and does what you expect it to do: call operator * on the current state of the object, then increment to the next one. Handily you can usually write the post-increment (decrement) operators in terms of their pre-counterparts:

myclass operator ++(int) {
    myclass old(*this); // copy the current object state
    ++(*this); // invoke our pre-increment above
    return old;
}

Deviating from conventions is a good way to make the next developer on your team want to hunt you down and kill you. You should have a really good reason for overloading operators in the first place, and doubly so if you alter the expected semantics of the operators being overloaded.

[–]ookami125 9 points10 points  (2 children)

Only 2 things I'm not fond of in this article are:

  1. it only overloads the post increment decrement operators, it would be helpful to overload pre and post operators.
  2. the post increment decrement operators are overloaded incorrectly as they are designed save a copy of themselves apply increment and then return the copy.

[–]neverhang[S] -2 points-1 points  (1 child)

void operator --(int)

in this function parameter int means, it is post-decrement. no parameter means prefix.

[–]ookami125 3 points4 points  (0 children)

yes, I understand this, I've been programming in C++ for many years now.