title: Friend functions and namespaces
body: <p>I'm trying to overload the &lt;&lt; operator for a class that's part of a user-defined namespace. What's interesting is that if I remove all that namespace stuff, the program compiles and runs without a problem, but the fact that the class resides in a namespace somehow makes the compilation process for the file A.cpp fail with an error saying that I'm trying to access private data in class A (demo.cpp compiles fine). Please, take a look at my three-file program and the compilation error that I get:</p>
  
  <p>demo.cpp:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "A.h"
  
  
  int main() {
      usr::A a(4);
      std::cout &lt;&lt; a &lt;&lt; std::endl;
  
  
      return 0;
  }
  </code></pre>
  
  <p>A.h:</p>
  
  <pre><code>#ifndef A_H_
  #define A_H_
  
  #include &lt;iostream&gt;
  
  
  namespace usr {
      class A {
          private:
              int m_x;
          public:
              A(int x);
              friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const usr::A&amp; a);
      };
  }
  
  #endif // A_H_
  </code></pre>
  
  <p>A.cpp:</p>
  
  <pre><code>#include "A.h"
  
  
  usr::A::A(int x) : m_x(x) {}
  
  std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const usr::A&amp; a) {
      os &lt;&lt; a.m_x;
      return os;
  }
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>$ g++ -c A.cpp
  In file included from A.cpp:1:0:
  A.h: In function ‘std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const usr::A&amp;)’:
  A.h:10:17: error: ‘int usr::A::m_x’ is private
               int m_x;
                   ^
  A.cpp:7:13: error: within this context
       os &lt;&lt; a.m_x;
               ^
  </code></pre>