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?