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

maccard picture maccard · Jan 31, 2012 · Viewed 12.4k times · Source

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?

Answer

Matteo Italia picture Matteo Italia · Jan 31, 2012

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.