Operator overload member or non member

Mar 10, 2012 at 5:47pm
Hi,I am studing operator overloading right now ,is there any rule if the operator overload should be member or non member of the class
Thanks
Mar 10, 2012 at 5:50pm
closed account (zb0S216C)
The operator can be internal or external to the class. However, there's two things you need to note:

1) The internally overloaded operator has precedence over the externally overloaded operator.
2) The externally overloaded operator cannot access private members, unless it's a friend.

Wazzak
Mar 10, 2012 at 6:23pm
These are effectively equivalent:

1
2
3
4
5
class MyClass
{
public:
    MyClass& operator+(int b);
};

and
1
2
3
4
5
6
7
class MyClass
{
public:
    friend MyClass& operator+(MyClass& a, int b);
};

MyClass& operator+(MyClass& a, int b);


If you drop the friend definition in the class, then the function cannot access private members of MyClass;

If you want the class to be on the right of the operator (such as for cout << MyObject), then you need to use the friend method.
Last edited on Mar 10, 2012 at 6:33pm
Topic archived. No new replies allowed.