title: overriding virtual function return type differs and is not covariant
body: <p>Ah, SO came back just in time.</p>
  
  <p>I am getting a strange error:</p>
  
  <pre><code> 'B::blah': overriding virtual function return type differs and is not covariant from 'A::blah'
  </code></pre>
  
  <p>Here is the code causing the problem:</p>
  
  <pre><code>class A {
  public:
      class Inner { };
  
      virtual Inner blah() = 0;
  };
  
  class B : public A {
  public:
      class Inner2 : public Inner { };
  
      Inner2 blah() {
          return Inner2();
      }
  };
  </code></pre>
  
  <p>I looked up the error, and according to <a href="http://support.microsoft.com/kb/240862" rel="noreferrer">a page I found on the Microsoft website</a>, one of the ways types can be covariant is if:</p>
  
  <blockquote>
    <p>the class in the return type of B::f is the same class as the class in the return type of D::f or, is an unambiguous direct or indirect base class of the class in the return type of D::f and is accessible in D</p>
  </blockquote>
  
  <p>Is that not the case with <code>Inner</code> and <code>Inner2</code>? I am using Microsoft Visual C++ 2010 if it matters.</p>
  
  <hr />
  
  <p>OK, so thanks to John I learned that only pointers and references can be covariant. Why is that? A Derived can be cast to a Base, so why don't virtual functions with return types that are derived from the same thing just cast the return type to the one of the base class? In my example, it seems like it would make sense to have <code>(A*(new B))-&gt;blah()</code> return a <code>Inner</code> that is really an <code>Inner2</code> that has been cast up.</p>