Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return type of overloading assignment operator in c++ [duplicate]

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 ?

like image 728
kaushik Avatar asked Dec 10 '22 00:12

kaushik


2 Answers

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.

like image 173
Vincenzo Pii Avatar answered Apr 02 '23 11:04

Vincenzo Pii


Returning *this allows you to chain assignments like this,

SimpleCircle a, b, c(10);
a = b = c;
like image 29
Hindol Avatar answered Apr 02 '23 11:04

Hindol