title: C++ Covariance and references
body: <p>Lets say I have an abstract base class with a pure virtual that returns an expensive object.  As it's an expensive object, I should return a reference to it.</p>
  
  <p>But life's not that simple, let's say I have two classes derived from it: one has the function called often, so it is more efficient to store a copy in the instance and return a reference.  The other is called rarely, so it is better to create the object on demand to save RAM.</p>
  
  <p>I thought I could just use covariance because the Liskov substitution principle would be happy, but of course <code>Obj</code> is not a subtype of <code>Obj&amp;</code>, so compile errors result.</p>
  
  <pre><code>class abc
  {
  public:
      virtual BigObj&amp; obj() = 0;
  };
  
  class derived : public abc
  {
  public:
      ...
      virtual BigObj obj() { return obj_; }
  
  private:
      BigObj obj_;
  };
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code>conflicting return type specified for ‘virtual BigObj derived::obj()’
  </code></pre>
  
  <p>Is there a more elegant solution to this than simply picking the least worst?</p>