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 ?
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+bshould return a new object, while fora+=bit 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:
and this:
The second version passes one argument by value, resulting in simpler code and giving the compiler more opportunities to elide temporary copies.