Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overloaded assignment operator return reference to class?

Tags:

c++

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.
like image 898
sukumar Avatar asked Sep 09 '11 11:09

sukumar


People also ask

Why do we return reference in copy assignment operator?

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.

What does the assignment operator return?

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.

Why would you overload operators for your classes?

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).

Why a class should have both a copy constructor and an overloaded assignment operator?

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.


2 Answers

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.

like image 84
Johannes Schaub - litb Avatar answered Sep 29 '22 00:09

Johannes Schaub - litb


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.

like image 43
Vlad Avatar answered Sep 29 '22 00:09

Vlad