class item {
public:
item& operator=(const item &rh) {
...
...
return *this;
}
};
Is the following signature wrong?
void operator=(const item &rh);
item a, b;
a = b; // equivalent to a.operator=(b); so there is no need to return this.
If you return a reference, minimal work is done. The values from one object are copied to another object. However, if you return by value for operator= , you will call a constructor AND destructor EACH time that the assignment operator is called!! a = b = c; // calls assignment operator above twice.
The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
It allows you to provide an intuitive interface to users of your class, plus makes it possible for templates to work equally well with classes and built-in/intrinsic types. Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes).
Both the copy constructors and assignment operators copies from one object to another then why do we need both? Copyconstructor means it creates a new object and copies the contents from another exist object and assignment operator copies the contents from one existing object to the already existing object.
It is not "wrong", but surprising. An assignment evaluates to the target object. That's what the builtin meaning is. If you define it different for your own class, people could become confused.
Example:
int c;
while((c = getchar()) != EOF) {
// ...
}
The assignment to c
returned c
itself and compared it to EOF
afterwards. Users would expect your item
class to behave similar.
The signature with void would not allow chained assignments:
a = b = c;
(Look at Johannes' answer for one more example of a usage pattern based on assignment returning the assigned value.)
That's why using such signatures is discouraged. However, if I am not mistaken, you actually can use such a signature.
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