title: overloading << operators and inherited classes
body: <p>I've got a base class and then several derived classes. I would like to overload the "&lt;&lt;" operator for these derived classes. For normal operators, i.e. '+', virtual functions do the trick. What I understand to be the standard convention is to declare</p>
  
  <pre><code>friend ostream&amp; operator&lt;&lt;(ostream&amp; out, MyClass&amp; A);
  </code></pre>
  
  <p>within my class and then define the function after the class. A priori I would think adding virtual to the above definition would make it work, but after some thought (and errors from my compiler) I realize that doesn't make much sense. </p>
  
  <p>I tried a different tack on a test case, where all the class members are public. For example:</p>
  
  <pre><code>class Foo{
   //bla
  };
  
  ostream&amp; operator&lt;&lt;(ostream&amp; out, Foo&amp; foo){
    cout &lt;&lt; "Foo" &lt;&lt; endl;
    return foo;
  }
  
  class Bar : public Foo{
   //bla
  };
  
  ostream&amp; operator&lt;&lt;(ostream&amp; out, Bar&amp; bar){
    cout &lt;&lt; "Bar" &lt;&lt; endl;
    return bar;
  }
  
  ///////////////////////
  
  Bar bar = Bar();
  cout &lt;&lt; bar &lt;&lt; endl; // outputs 'Foo', not 'Bar' 
  </code></pre>
  
  <p>So in some way this is "polymorphism gone bad" -- the base class operator&lt;&lt; is being called rather than the derived class operator. In the above example, how do I make the correct operator get called for the derived class? And more generally, if my class has private members I want to protect, how can I correct the operator overloading while using the friend keyword?</p>