Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the assignment operator return a reference to the object?

Tags:

I'm doing some revision of my C++, and I'm dealing with operator overloading at the minute, specifically the "="(assignment) operator. I was looking online and came across multiple topics discussing it. In my own notes, I have all my examples taken down as something like

class Foo
{
    public:  
        int x;  
        int y;  
        void operator=(const Foo&);  
};  
void Foo::operator=(const Foo &rhs)
{
    x = rhs.x;  
    y = rhs.y;  
}

In all the references I found online, I noticed that the operator returns a reference to the source object. Why is the correct way to return a reference to the object as opposed to the nothing at all?

like image 451
maccard Avatar asked Jan 30 '12 23:01

maccard


People also ask

What should 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.

What happens when you use an assignment operator with objects?

The assignment operator (operator=) is used to copy values from one object to another already existing object. The purpose of the copy constructor and the assignment operator are almost equivalent -- both copy one object to another.

What is the purpose of the assignment operator?

An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands.


2 Answers

The usual form returns a reference to the target object to allow assignment chaining. Otherwise, it wouldn't be possible to do:

Foo a, b, c;
// ...
a = b = c;

Still, keep in mind that getting right the assigment operator is tougher than it might seem.

like image 169
Matteo Italia Avatar answered Sep 25 '22 17:09

Matteo Italia


The return type doesn't matter when you're just performing a single assignment in a statement like this:

x = y;

It starts to matter when you do this:

if ((x = y)) {

... and really matters when you do this:

x = y = z;

That's why you return the current object: to allow chaining assignments with the correct associativity. It's a good general practice.

like image 17
Borealid Avatar answered Sep 26 '22 17:09

Borealid