2

Possible Duplicate:
Overload operators as member function or non-member (friend) function?

In process of learning operator overloading in C++ I have seen two different types of overloading operator +.

I need your help to tell me which method is better to use: Method first:

Complex Complex::operator + (Complex &obj) {
   return Complex( re + obj.re, im + obj.im );
}

Method second:

Complex operator + (const Complex &obj1, const Complex &obj2) { 
    // this function is friend of class complex
    return Complex(obj1.re + obj2.re, obj1.im + obj2.im);
}

Thank you!!!

Community
  • 1
  • 1
depecheSoul
  • 896
  • 1
  • 12
  • 29
  • Does [this](http://stackoverflow.com/q/1145022/220636) or [that](http://stackoverflow.com/q/8509046/220636) help? – nabulke Apr 16 '12 at 10:19
  • @TonyDelroy thanks I did not notice it before – depecheSoul Apr 16 '12 at 10:19
  • 1
    @depecheSoul Please don't mark questions answered by adding 'solved' in the tile. Accept the best answer. Have a look at the FAQ to get used to StackOverflow and enjoy your time here. – pmr Apr 16 '12 at 10:29

2 Answers2

4

As long as there can be no implicit conversions, both are equally good; it's more a matter of taste. If there can implicit conversions to Complex (which in this case seems likely), then with the first form, implicit conversions will only work on the second argument, e.g.:

Complex c;
Complex d;

d = c + 1.0;    //  Works in both cases...
d = 1.0 + c;    //  Only works if operator+ is free function

In such cases, the free function is by far the preferred solution; many people prefer it systematically, for reasons of orthogonality.

In many such cases, in fact, the free function operator+ will be implemented in terms of operator+= (which will be a member):

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

In fact, it's fairly straightforward to provide a template base class which provides all of these operators automatically. (In this case, they're declared friend, in order to define them in line in the template base class.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329
1

Bjarne Stroustrup suggests you use the second form, for cases where you don't modify object itself or when you produce new value/object based on the provided arguments.

Mladen Janković
  • 7,867
  • 3
  • 22
  • 26
  • Interesting. I thought it wasn't a matter of preference, but simply of necessity. For instance when you want to implement `+=` or `scalar+class`, you have to use one form or the other. – Mr Lister Apr 16 '12 at 10:25