Question

while googling for how to overload operator = I found that some examples return value http://www.cprogramming.com/tutorial/operator_overloading.html
, while a friend of mine that is C++ guru long time ago told me to return reference. Also for example when I look at the STL source I saw stuff like:

  vector&
  operator=(const vector& __x);

so what is the correct way to do it ?

BTW if you are curious my friend told me that the reason why to return ref is beause built in types return l-value.

int x;
(x = 3) += 2;
// x is now 5.
Was it helpful?

Solution

Other than special cases where you really, really know what you're doing, it should return either class& or void. (And most of the time, returning void should just be a placeholder for "I'm being lazy and haven't gotten around to making sure that returning class& makes sense")

Returning class is a bad idea because it wastes time and memory (it makes a copy!) in the normal case where the user doesn't use the return value, and will thoroughly mislead a user who actually does use the return value (and still waste time making copies).

OTHER TIPS

Yes, it should return a reference-to-self.

Its always good to use the reference as both memory and time are saved.if you pass by value new object has to be created copy constructor will have to be called.which is more expensive with respect to time as well as memory.

so pass it by reference always unless you have a very strong necessity to be passed/returned by value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top