As I've understand, when overloading operator=, the return value should should be a non-const reference.
A& A::operator=( const A& )
{
// check for self-assignment, do assignment
return *this;
}
It is non-const to allow non-const member functions to be called in cases like:
( a = b ).f();
But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?
It's assumed that copy constructor is implemented correctly.
The overloading assignment operator can be used to create an object just like the copy constructor. If a new object does not have to be created before the copying occurs, the assignment operator is used, and if the object is created then the copy constructor will come into the picture.
Overloading the assignment operator (operator=) is fairly straightforward, with one specific caveat that we'll get to. The assignment operator must be overloaded as a member function. This will call f1. operator=(f1), and under the simplistic implementation above, all of the members will be assigned to themselves.
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type.
Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?
a = b; // huh, why does this create an unnecessary copy?
In addition, it would be surprising to users of your class, since the built-in assignment operator doesn't copy likewise
int &a = (some_int = 0); // works
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