Possible Duplicate:
Why must the copy assignment operator return a reference/const reference?
Operator= overloading in C++
I have already asked a question about this assignment operator overloading. I may be asking a foolish question. Pardon me.
My class declaration is like this:
class Circle
{
public:
Circle();
Circle(const Circle &);
Circle(unsigned short rad);
unsigned short getRadius() const { return itsradius; }
void setRadius(unsigned short rad) { itsRadius = rad; }
private:
unsigned short itsRadius:
};
My class definition:
Circle::Circle()
{
itsRadius = 0;
}
Circle::Circle(unsigned short rad)
{
itsRadius = rad;
}
Circle::Circle(const Circle & rhs)
{
itsRadius = rhs.getRadius();
}
I am overloading assignment operator like this:
SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
itsRadius = rhs.getRadius();
return *this;
}
When we are working on the current object like "itsRadius = rhs.getRadius()", the current object's radius will be changed, then, what is the need for returning "*this" ? Can this function be re-written as a void one ? Is there any problem with it ? Or is it just a standard to follow ?
It allows you to assign to multiple instances in one statement like this:
Returning
*this
allows you to chain assignments like this,It's convention, see wikipedia, and the linked article by Richard Gillam.
That is a good convention to follow to be consistent with the behavior of
operator=
for built-in types.With built-in types you can do something like this:
If you do not return the reference to
*this
, the assignment chain won't be supported by your type.