title: Overriding functions (from two abstract base classes) that differ only by their return value
body: <p>I want to create a class that implements two interfaces that have functions with a same name that differ only by their return values. How can I do this correctly?</p>
  
  <pre><code>template&lt;class T&gt;
  class IBase
  {
  public:
      virtual T Method() = 0;
  };
  
  class Derived : public IBase&lt;int&gt;, public IBase&lt;char&gt; {
  public:
      int _value;
  
      virtual int IBase&lt;int&gt;::Method();
      virtual char IBase&lt;char&gt;::Method();
  };
  
  int Derived::Method() {
      return _value;
  }
  
  char Derived::Method() {
      return _value;
  }
  </code></pre>
  
  <p>Here are the errors that I get:</p>
  
  <pre><code>error C2555: 'Derived::Method: overriding virtual function return type differs and is not covariant from 'IBase&lt;int&gt;::Method
  
  error C2556: 'int Derived::Method(void)' : overloaded function differs only by return type from 'char Derived::Method(void)'
  
  error C2371: 'Derived::Method: redefinition; different basic types
  
  error C2084: function 'char Derived::Method(void)' already has a body
  </code></pre>
  
  <p>In C# it's pretty easy to do this without any ambiguities using nearly same syntax (called explicit interface implementation):</p>
  
  <pre><code>class Derived : IBase&lt;int&gt;, IBase&lt;char&gt; {
      int _value;
  
      int IBase&lt;int&gt;.Method() {
          return _value;
      }
  
      char IBase&lt;char&gt;.Method();
          return _value;
      }
  };
  </code></pre>
  
  <p>Explicitly implementations are private and thus cannot be used directly on variables of class <code>Derived</code>. They are still very usable though as you can cast the <code>Derived</code> to one of the interfaces to use the implementation:</p>
  
  <pre><code>var d = new Derived();
  ((IBase&lt;int&gt;)d).Method();
  </code></pre>
  
  <p>This can be rather useful. A class can implement ICanConvertTo many times to enable different conversions.</p>