5
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.
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
sukumar
  • 161
  • 2
  • 6

3 Answers3

10

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.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
6

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.

Vlad
  • 35,022
  • 6
  • 77
  • 199
2

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.

Archie
  • 6,391
  • 4
  • 36
  • 44
  • 1
    Not only that, declaring `operator=` as returning `void` you won't be able to use the result of the assignment into any expression. – Matteo Italia Sep 09 '11 at 11:18