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 ?
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:
int a, b, c;
// ...
a = b = c = 10;
If you do not return the reference to *this, the assignment chain won't be supported by your type.
Returning *this allows you to chain assignments like this,
SimpleCircle a, b, c(10);
a = b = c;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With