title: C++ operator << print object address
body: <p>Is it possible to have a class with overloaded ostream operator &lt;&lt; , (as following code)
  to print out the address of that instance?</p>
  
  <pre><code>class MyCls {
        friend ostream&amp; operator &lt;&lt; (ostream&amp; o, const MyCls&amp; c) { return o &lt;&lt; "MyClass\n";  }
        friend ostream&amp; operator &lt;&lt; (ostream&amp; o, const MyCls *c) { return operator&lt;&lt;(o, *c); }
  };
  MyCls a, b;
  std::cout &lt;&lt; a &lt;&lt; b;
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>(0x12345678) MyClass
  (0x23456789) MyClass
  </code></pre>
  
  <p>Any workaround?</p>
  
  <p>[Edit]</p>
  
  <h2>Scenario</h2>
  
  <p>I skipped quite a lot details of MyCls to make the question seems simple. The class actually has vectors of pointers to other classes. Those classes also have ostream operators overloaded in similar fashion. So my primary aims is to show which objects is contained in which containers. </p>
  
  <pre><code>class MyClsB {};
  class MyCls {std::vector&lt;MyClsB *&gt; containers; std::string attrA;};
  
  class Printer() {
      void operator() (const T&amp; arg) { os &lt;&lt; arg;}
      void operator() (T *arg) { os &lt;&lt; *arg; }
      }
  
  int main(int c, char** a) {
      std::vector&lt;MyCls *&gt; v;
      //version 1
      for (int i = 0; i &lt; v.size(); i++) std::cout &lt;&lt; v[i] &lt;&lt; "\n";
          //version 2
          for_each(v.begin(), v.end(); Printer(std::cout));
          return 0;
  }
  </code></pre>
  
  <p>Expected output</p>
  
  <pre><code>(0x12345678) MyCls: attrA = v1
  (0x1234abcd) MyClsB
  (0x1234defg) MyClsB
  (0x23456789) MyCls: attrA = v2
  (0x2345abcd) MyClsB
  ...
  </code></pre>
  
  <h2>Platform</h2>
  
  <ul>
  <li>Win 7x64: VS2010 express</li>
  <li>Linux   : gcc 4.4.5</li>
  </ul>
  
  <p>[Edit 1]: I tried Benjamin's method, and it simply gives segmentation fault to me. Adding some debug print shows that Benjamin's method just go into infinite loop.</p>
  
  <p>[Edit 2]: For Jerry's suggestion, my compiler complains "invalid static_cast from type ‘const MyCls*’ to type ‘void*’" (gcc 4.4.5)</p>
  
  <p>[Edit 3]: Removing the pointer-version of operator&lt;&lt; just print the address but nothing more, which violated my primary goal. I think it's because not declaring pointer-version will use default implementation which just print the address only. </p>
  
  <p>Why I declare pointer-version is to simplify the calling statement. Instead of </p>
  
  <pre><code>std::cout &lt;&lt; *p2Obj
  </code></pre>
  
  <p>just</p>
  
  <pre><code>std::cout &lt;&lt; p2Obj
  </code></pre>
  
  <p>Also, I have a functor object which is used to combine with for_each() calls <a href="https://stackoverflow.com/questions/9530859/member-function-to-a-list-of-pointer">my previous question</a></p>