27

In C++, i know there are two ways to overload. We can overload it inside (like class a) or outside (like class b). But, the question is, is there any difference between these two either in compile time or runtime or not?

class a
{
public:
    int x;
    a operator+(a p) // operator is overloaded inside class
    {
        a temp;
        temp.x = x;
        temp.x = p.x;
        return temp;
    }
};

class b
{
public:
    friend b operator+(b, b);
    int x;
};

b operator+(b p1, b p2) // operator is overloaded outside class
{
    p1.x += p2.x;
    return p1;
}
Azeem
  • 11,148
  • 4
  • 27
  • 40
Ali1S232
  • 3,373
  • 2
  • 27
  • 46
  • 1
    possible duplicate of [operator overloading(friend and member function)](http://stackoverflow.com/questions/2770745/operator-overloadingfriend-and-member-function) – interjay Apr 03 '11 at 22:43
  • 2
    Outside the scope of the question: But both addition operators are incorrectly implemented. Operators should be overloaded to behave as expected. Normally (apart from += etc) operators do not modify there parameters (so pass by const reference and the member operator should be const. – Martin York Apr 03 '11 at 23:10

1 Answers1

25

The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to b

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}
Erik
  • 88,732
  • 13
  • 198
  • 189