class item {
public:
item& operator=(const item &rh) {
...
...
return *this;
}
};
Is the following signatur
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.
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.
It's perfectly legal. But when you declare operator=
like that, you will be unable to make "chain of assignment":
item a(X);
item b;
item c;
c = b = a;
Reference allows modifying returned value. Since operator=
is evaluated from right to left, the usage I showed to you is working.
EDIT Also, as others mentioned, return value is often used in expressions like while (a = cin.get()) != 'q')
. But you also can declare operator like A operator=(const A&)
(returns copy) or const A& operator(const A&)
(returns const reference). My point is: this operator can return anything, but the idiomatic way is to return non-const reference to itself.