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

8
  • 3
    What happened when you tested both of those yourself? Commented Feb 11, 2014 at 17:29
  • They both seem to work fine, but I don't know which one is right Commented Feb 11, 2014 at 17:30
  • 1
    The reference return is "correct" (its an lvalue thing). See this answer and scroll down to the appropriate subsection. Commented Feb 11, 2014 at 17:31
  • 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. Commented Feb 11, 2014 at 17:34
  • 2
    Maybe the question was downvoted because it doesn't show any research effort Commented Feb 11, 2014 at 17:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which function is prefix: operator(int)++ or operator()++? I know one of them takes a parameter: forums.codeguru.com/…
@ThomasMatthews the one I said in my answer :-)
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.