Why does an overloaded assignment operator return a reference to a class?

class item {
public:
    item& operator=(const item &rh) {
        ...
        ...
        return *this;
    }
};

Is the next signature incorrect?

void operator=(const item &rh);

item a, b;
a = b; // equivalent to a.operator=(b); so there is no need to return this.
+5
source share
3 answers

This is not “wrong," but surprising. Destination evaluates the target. This is what has a built-in meaning. If you define it differently for your class, people may get confused.

Example:

int c;
while((c = getchar()) != EOF) {
  // ...
}

The assignment creturned cand then compared it to EOF. Users would expect your class itemto behave similarly.

+10
source

A signature with void will not allow you to assign a chain:

a = b = c;

( , , .)

. , , ​​.

+5

. operator= , " ":

item a(X);
item b;
item c;
c = b = a;

. operator= , , , .

EDIT Also, as mentioned above, the return value is often used in type expressions while (a = cin.get()) != 'q'). But you can also declare an operator like A operator=(const A&)(returns a copy) or const A& operator(const A&)(returns a link constant). I want to say that this operator can return anything, but the idiomatic way is to return a non-constant reference to itself.

+2
source

All Articles