title: If I have a collection of superclass type, how do I get all the items of a specific subclass type?
body: <p>I want to create a collection in C++ of type Parent, where I add different subclasses like Child and Child2, and then get all the elements of X subclass. I tried with a vector, but it happens to destroy polymorphism according to <a href="https://stackoverflow.com/questions/5200663/virtual-functions-iterating-over-a-vectorbase-class-that-is-populated-with-su">this answer</a>. If I use a collection of pointers, I would have to iterate over it sequentially checking the class of every element, is there a better / more efficient solution?</p>
  
  <p>Here's an example code:</p>
  
  <pre><code>class Parent
  {
     public:
       int id;
       Parent(){ id = 8; }
  };
  
  class Child: public Parent
  {
       int foo;
     public:
       Child(int n){ foo= n; }
  };
  
  class Child2: public Parent
  {
       int bar;
     public:
       Child2(int n){ bar= n; }
  };
  </code></pre>
  
  <p>Pseudocode:</p>
  
  <pre><code>GenericCollection&lt;Parent&gt; collection; //Full of elements Child and Child2.
  </code></pre>
  
  <p>This is the method I want to implement:</p>
  
  <pre><code>collection.getElements&lt;Child2&gt;();
  </code></pre>
  
  <p>Thanks for everything.</p>