I was recently going over an article on operator overloading in which it mentioned non-member operator overloading. I would appreciate it if someone could explain what is meant by non-member operator overloading with an example. I know what member operator overloading is (A method in a class which overloads an operator type (binary..etc) . I came across this post on SO which makes me believe that the purpose of non-member operator overloading is to handle operator overloading in which the first parameter is a not a class and is simply a native type. Any links or examples that explain what non-member operator overloading is would definitely be appreciated.
-
The link you gave shows an example for non member operator overloading, used as you said to perform add on a primitive – omer schleifer Mar 17 '13 at 21:57
-
[This](http://stackoverflow.com/q/4421706/1410711) might be helpful... – Recker Mar 17 '13 at 21:57
2 Answers
It means you can overload out-of-class:
struct X { int data; };
bool operator<(X const& a, X const& b)
{
return a.data < b.data;
}
This is useful for assymetrical overloading, where the left operand doesn't need to be your own type:
bool operator<(int a, X const& b)
{
return a < b.data;
}
A common idiom here is to combine it with in-class definition and friend declaration:
struct X
{
int data;
friend bool operator<(X const& a, X const& b) { return a.data<b.data; }
friend bool operator<(int a, X const& b) { return a<b.data; }
};
Here, operator<
is still technically non-member.
Another useful side-effect of this, as pointed out by DrewDormann below, is that the (X const&, X const&)
will apply to any operands that are implicitly convertible to X const&
, not just expressions of that exact type.

- 374,641
- 47
- 450
- 633
-
It's also useful for *symetrical* type conversion, allowing implicit type conversions for all involved operands. – Drew Dormann Mar 17 '13 at 21:59
the most common way is to overload operator<< that will be called on std::cout
:
namespace X {
class MyClass {
...
};
}
std::ostream& operator<< (std::ostream&, const X::MyClass&);
this is called on std::ostream member so you don't define it inside your class. however sometimes the functionality cannot be achieved via the public interfaces (because your operator needs access to data representation).

- 29,204
- 9
- 82
- 118