Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C ++ operator overload ++

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

like image 789
Ziyad Mestour Avatar asked Dec 20 '22 18:12

Ziyad Mestour


2 Answers

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

like image 164
juanchopanza Avatar answered Jan 22 '23 10:01

juanchopanza


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

like image 39
Sebastian Redl Avatar answered Jan 22 '23 10:01

Sebastian Redl