I had a doubt in the overloaded copy assignment operator. I read it in many books/websites that the signature for overloaded copy assignment operator looks like as follows:
Type &Type::operator=(const Type &rhs)
However, I dont understand why do we need to return it by reference, in fact doesnt it makes sense to return nothing? I mean when we return it by reference or by value, where is the return value being returned to since the other object has already being assigned in the overloaded copy asssignment operator For eg. If I have something like this in my main function:
int main(){
Type a {<Some lieral value>}; //Initialise object a with some literal
Type b {<Some literal value>};
b=a; //Object b is already assigned when we call overloaded copy operator, which variable accepts the return value?
}
Note: The book/website says something about chain assignment, howver I dont understand where the value will be returned to when we have the above case.
Type b = a;
doesn't invoke a copy assignment operator. It invokes a copy constructor. – Igor Tandetnik*this
allows chaining assignments, as ina = b = c;
The thinking is, if it works forint
s there is no reason it shouldn't work for your objects. – Igor TandetnikT c; c = b = a;
then a return value fromb=a
will in fact be used. – Igor Tandetnikoperator=
, you wouldn't know whether, at some later time, someone might want to chain-assign your objects. It's perfectly valid to ignore a return value of any function; happens all the time. – Igor Tandetnik