2

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.

Community
  • 1
  • 1
MistyD
  • 13,289
  • 28
  • 108
  • 198

2 Answers2

4

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.

sehe
  • 328,274
  • 43
  • 416
  • 565
0

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).

4pie0
  • 27,469
  • 7
  • 70
  • 110