title: c++ problem with polymorphism and vectors of pointers
body: <p>Consider the following example code:</p>
  
  <pre><code>class Foo
  {
  };
  
  class Bar : public Foo
  {
  };
  
  class FooCollection
  {
  protected:
      vector&lt;shared_ptr&lt;Foo&gt; &gt; d_foos;
  };
  
  class BarCollection : public FooCollection
  {
  public:
      vector&lt;shared_ptr&lt;Bar&gt; &gt; &amp;getBars()
      {
          // return d_foos won't do here...
      }
  };
  </code></pre>
  
  <p>I have a problem like this in my current project. The client code uses <code>BarCollection</code>, which stores pointers to <code>Bars</code> in <code>d_foos</code> which is declared in <code>FooCollection</code>. I'd now like to expose the collection of pointers to Bars to the client code. I could just give the client code access to the vector of pointers to <code>Foo</code>s and cast these to pointers to <code>Bar</code>s in the client code, but this feels wrong since the client doesn't have to know about <code>Foo</code>'s existence.</p>
  
  <p>I could also define a <code>get()</code> member that retrieves objects from <code>d_foos</code> and casts them, but this feels quite clumsy. Preferably, I'd like to just return d_foos as a <code>vector&lt;shared_ptr&lt;Bar&gt; &gt; &amp;</code>, but I cannot seem to do this.</p>
  
  <p>It could also be that my design is just plain wrong. It seemed to most natural solution though, as <code>Bar</code> is a specialization of <code>Foo</code> and <code>BarCollection</code> is a specialization of <code>FooCollection</code> and they share functionality.</p>
  
  <p>Could you suggest nice solutions to implement <code>getBars</code> in <code>BarCollection</code> or better design alternatives?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Turns out my design was bad indeed. BarCollection is not a FooCollection, despite of requiring all of FooCollection's functionality. My current solution based on the answers below -- which is a lot cleaner -- is now:</p>
  
  <pre><code>class Foo
  {
  };
  
  class Bar : public Foo
  {
  };
  
  template&lt;class T&gt;
  class Collection
  {
      vector&lt;shared_ptr&lt;T&gt; &gt; d_items;
  };
  
  typedef Collection&lt;Foo&gt; FooCollection;
  
  class BarCollection : public Collection&lt;Bar&gt;
  {
      // Additional stuff here.
  };
  </code></pre>
  
  <p>Thanks for all the excellent suggestions and examples!</p>