4

which one of the two codes is right and why ?

C C::operator++() {
    x++; 
    y++; 
    return *this; 
}


C & C::operator++() {
    x++; 
    y++; 
    return *this; 
}

Thanks

admdrew
  • 3,790
  • 4
  • 27
  • 39
  • 3
    What happened when you tested both of those yourself? – admdrew Feb 11 '14 at 17:29
  • They both seem to work fine, but I don't know which one is right – Ziyad Mestour Feb 11 '14 at 17:30
  • 1
    The reference return is "correct" (its an lvalue thing). See [this answer](http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719) and scroll down to the appropriate subsection. – WhozCraig Feb 11 '14 at 17:31
  • I would optate for the second (&C return) – thedarkside ofthemoon Feb 11 '14 at 17:32
  • 3
    As comments and answers mentiom, the second is "more" correct. PS: to whomever downvoted the question, please mention why. It's a well-formed and interesting question and does not deserve a negative score. – David Titarenco Feb 11 '14 at 17:34
  • 2
    Maybe the question was downvoted because it doesn't show any research effort – anatolyg Feb 11 '14 at 17:35
  • This is not a question about research, as use of `&` is a point of contention, especially in examples like above. Also, consider the OP's second post in which he said that he compiled both but wasn't sure which one is correct -- given that the answer is nontrivial (and involved in the muddy topic known as idiomatic C++ and lvalue/rvalue semantics), I'd say OP did as much research as would be required before asking the question. I guess I'm just a bit irked at SO's recent "reddit mentality" of downvote first, ask questions later. – David Titarenco Feb 11 '14 at 17:58
  • While baking one's noodle on these, you can add in thoughts on `C& operator ++()&;` – WhozCraig Feb 11 '14 at 18:10

2 Answers2

7

The second one is the idiomatic one: a parameter-less operator++ is the pre-fix increment operator, which should return a reference to self.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Which function is prefix: `operator(int)++` or `operator()++`? I know one of them takes a parameter: http://forums.codeguru.com/showthread.php?231051-C-Operator-How-to-overload-postfix-increment-and-decrement-operators – Thomas Matthews Feb 11 '14 at 20:49
  • @ThomasMatthews the one I said in my answer :-) – juanchopanza Feb 11 '14 at 20:50
4

Both are "correct", but the second is idiomatic, because it's expected that the prefix operator ++ returns an lvalue.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157