By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 454,912 Members | 1,247 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,912 IT Pros & Developers. It's quick & easy.

# Why return *this

 P: n/a In one of the books, the author writes: Class Complex { .... Complex& operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; return *this; } .... } Why cant it just be void operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; } Jul 27 '05 #1
Share this Question
3 Replies

 P: n/a wrote in message news:11**********************@g14g2000cwa.googlegr oups.com... In one of the books, the author writes: Class Complex { ... Complex& operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; return *this; } ... } Why cant it just be void operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; } It could be... but then the result couldn't be used in an expression. Why limit yourself? -Howard Jul 27 '05 #2

 P: n/a bl**********@gmail.com wrote: In one of the books, the author writes: Class Complex { ... Complex& operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; return *this; } ... } Why cant it just be void operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; } It can, but shouldn't. A good rule for operator overloading is: "do it as int does". And you can e.g. write: a = b = c; Therefore, it's good to return a reference to an object, so that you can use the assignment in other expressions. Jul 27 '05 #3

 P: n/a bl**********@gmail.com wrote in news:1122487180.619994.180790 @g14g2000cwa.googlegroups.com: In one of the books, the author writes: Class Complex { ... Complex& operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; return *this; } ... } Why cant it just be void operator+=(const Complex& Other) { real_+=Other.real_; im_+=Other.im_; } So that one can do: Complex x; x += othercomplex += thirdcomplex; Jul 27 '05 #4

### This discussion thread is closed

Replies have been disabled for this discussion.