Question: > 
> **Possible Duplicate:**  
> 
> [Where should non-member operator overloads be placed?](https://stackoverflow.com/questions/3623631/where-should-non-member-operator-overloads-be-placed) 
> 
> 
> 

While browsing on SO, I often find questions or answer that involves overloading/defining a `std::ostream& operator<<(std::ostream& os, const Foo& foo)` or a `Foo operator+(const Foo& l, const Foo& r)`.

While I know how and when (not) to write these operators, I'm confused about the `namespace` thing.

If I have the following class:

```
namespace bar
{
  class Foo {};
}

```

In which `namespace` should I write the different operator definitions ?

```
// Should it be this

namespace bar
{
  std::ostream& operator<<(std::ostream& os, const Foo& foo);
}

// Or this ?

namespace std
{
  ostream& operator<<(ostream& os, const bar::Foo& foo);
}

// Or this ?

std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);

```

The same question applies for the `operator+`. So, what is the good practice here and **why** ?

Answer: 
It should be in the `bar` namespace. You must consider [what makes up the interface for the class](http://www.gotw.ca/publications/mill02.htm), and group those together.

"A class describes a set of data along with the functions that operate on that data." Your free function operates on a `Foo`, therefore it is part of `Foo`. It should be grouped with `Foo` in the namespace `bar`.

[Argument-dependent lookup](http://en.wikipedia.org/wiki/Argument-dependent_name_lookup), or ADL, will find the function.

We also know that we should [prefer non-friend non-member functions](http://www.drdobbs.com/184401197). What this means is that, in general, your classes will have their definition and member functions, followed immediately by free functions which operate on the class.
The best choice is option 1.
Why? Because when you use a unqualified function name (an an overloaded operator is a function), apart from normal name lookup, Argument-Dependent lookup is applied, that is (informally) all the namespaces where the arguments were declared are searched. 
E.g.

```
namespace N
{
   class X(){};
   void f(X){}
}
int main()
{
    N::X x;
    f(x); //works fine, no need to qualify f like N::f
}

```

The same is with operators.

On the other hand, in case of option 2 the operator still will be found because ostream is in std (same ADL rule). But it is not a good idea to add stuff to std namespace.

And the third option is bad, stylistically - why do it if the first option is sufficient?

So, definitely option 1.

HTH.