0

Is it safe to write our own copy constructor always during operator overloading ?

Complex Complex::operator+(const Complex&  other)
{
    Complex local ;
    local.result_real = real + other.real;
    local.result_imaginary = imag + other.imag;
    return local ;
}

Most of the times i have seen the above format , instead of returning it as reference .

Can we take thumb rule like 1- Always pass the function parameter by reference . 2- Always return the object by reference .

Is there any special case in operator overloading where we have to return the object by value only ?

Viku
  • 2,845
  • 4
  • 35
  • 63
  • 1
    Did you mean: Never return by reference (unless you know exactly what you're doing). – melpomene Nov 30 '12 at 06:58
  • 1
    It depends on what operator your are overloading, see [Operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading), it will answer all your questions and more. – Jesse Good Nov 30 '12 at 07:01
  • Returning a local by reference will cause undefined behaviour. The only cases where you can return an object by reference are: 1) You are returning the current object through a method. 2) You create a new object and return its reference, handling somewhere its deletion. – Jean-Marie Comets Nov 30 '12 at 07:03

2 Answers2

1

Can we take thumb rule like 1- Always pass the function parameter by reference . 2- Always return the object by reference .

No, not really. Even if you found a way to return a non-dangling reference, an operation such as addition should not return a reference, since this does not make sense. a+b should return a new object, while for a+=b it does make sense to return a reference to the LHS.

Concerning passing an argument by reference, there is no rule of thumb either. Consider this:

A operator+(const A& lhs, const A& rhs)
{
  A tmp = lhs; // explicitly make a copy
  return tmp += rhs;
}

and this:

A operator+(A lhs, const A& rhs)
{
  return lhs += rhs;
}

The second version passes one argument by value, resulting in simpler code and giving the compiler more opportunities to elide temporary copies.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

For some operators you should return a reference, for others you should not, and still others return other types completely (like the comparison operators).

In your case you should not. Especially since you will then return a reference to a local variable which will not be valid when the function returns.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621