Why return *this

B

bluekite2000

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_;

}
 
A

Andre Kostur

(e-mail address removed) wrote in @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;
 
H

Howard

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
 
R

Rolf Magnus

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top