I have written following class which has overloaded assignment operator. As shown in example everywhere I returned *this
from assignment operator.
class Sample
{
int *p;
int q;
public:
Sample()
{
cout<<"Constructor called"<<endl;
p = new int;
q = 0;
}
Sample& Sample::operator =(const Sample &rhs)
{
cout<<"Assignment Operator"<<endl;
if(this != &rhs)
{
delete p;
p = new int;
*p = *(rhs.p);
}
return *this;
}
void display()
{
cout<<"p = "<<p<<" q = "<<q<<endl;
}
};
When I call assignment operator like a = b
, it goes like, a.operator=(b);
.
Now I am calling a's operator function, this is already being passed with operator =
then why it is required to return it from assignment operator?
You have to return *this (and also by reference) if you want to support chaining of assignment. For e.g
Class A
{
};
A x,y,z,w;
x = y = z = w; //For this you are returning *this.
EDITED FOR MORE CLARIFICATION:- ( In response to your comment )
Let's suppose you're not returning anything from your assignment operator then expression will be evaluated as follows:-
x=y=z => x=(y=z)
Above will result into a call to
y.operator(z)
as assignment operator is right associative. After this next call would be to
x.operator ( value returned from y=z) ).
If you don't return any value chaining would fail.
Hope I am clear