sukumar
sukumar

Reputation: 161

Why does overloaded assignment operator return reference to class?

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.

Upvotes: 5

Views: 2506

Answers (3)

Archie
Archie

Reputation: 6844

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.

Upvotes: 2

Vlad
Vlad

Reputation: 35594

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.

Upvotes: 6

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507005

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.

Upvotes: 10

Related Questions