DOUBT

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
goldenrust007
Posts: 4
Joined: January 25th, 2020, 8:54 am

DOUBT

Post by goldenrust007 » February 24th, 2020, 4:54 am

Why is it that when overloading an assignment operator, we need to return a reference ( *this ). I have overloaded the operator without returning anything and it seems to work fine.

User avatar
chili
Site Admin
Posts: 3948
Joined: December 31st, 2011, 4:53 pm
Location: Japan
Contact:

Re: DOUBT

Post by chili » February 25th, 2020, 1:50 am

You don't *have* to. But it is the expected behavior. The built-in uses of assignment operators will resolve to a reference to the left hand side.

It like asking "why walk on the right hand side" in countries with that custom. Certainly there may be no laws against walking on the other side. But you tend to bump into people more and generally make a nuisance of yourself. To what end?
Chili

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: DOUBT

Post by albinopapa » March 11th, 2020, 3:51 pm

Another reason for returning a reference would be for a slightly useful feature.

auto c = a = b = 2;
If your assignment operator returned void, chaining wouldn't be possible.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Post Reply