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!!!
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.:
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 beimplemented in terms of
operator+=(which will be a member):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 thetemplate base class.)