| View previous topic :: View next topic |
| Author |
Message |
bluekite2000@gmail.com Guest
|
Posted: Wed Jul 27, 2005 5:59 pm Post subject: Why return *this |
|
|
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_;
}
|
|
| Back to top |
|
 |
Andre Kostur Guest
|
Posted: Wed Jul 27, 2005 6:04 pm Post subject: Re: Why return *this |
|
|
[email]bluekite2000 (AT) gmail (DOT) com[/email] wrote in news:1122487180.619994.180790
@g14g2000cwa.googlegroups.com:
| Quote: | 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;
|
|
| Back to top |
|
 |
Howard Guest
|
Posted: Wed Jul 27, 2005 6:09 pm Post subject: Re: Why return *this |
|
|
<bluekite2000 (AT) gmail (DOT) com> wrote
| Quote: | 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
|
|
| Back to top |
|
 |
Rolf Magnus Guest
|
Posted: Wed Jul 27, 2005 6:34 pm Post subject: Re: Why return *this |
|
|
[email]bluekite2000 (AT) gmail (DOT) com[/email] wrote:
| Quote: | 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.
|
|
| Back to top |
|
 |
|