title: C++ templates with derived classes
body: <p>I'm writing a library, and in it I have a class BaseClass.  Anyone using the library will be creating their own classes that inherit from BaseClass.  I have another class, lets call it Manager, which holds a vector of BaseClass pointers, which can hold any object derived from BaseClass.</p>
  
  <p>The Manager class MUST handle the creation and destruction of any object added to its BaseClass vector.  This is because any object in the vector can be deleted at any time, and the Manager itself can also be deleted.  Because of this, the user of the library cannot add an object to the Manager's baseClass vector by passing it a pointer to an already existing object derived from BaseClass.  Well actually, I could allow the user to do that.  But that would involve copying a dummy object, which I'd rather not do.</p>
  
  <p>To solve this, I'm trying to use a template function.  The user should pass the type of the object derived from BaseClass when trying to add it to the Manager's vector.  This is what I currently have.</p>
  
  <pre><code>//Manager.h
  #include &lt;vector&gt;
  #include "BaseClass.h"
  #include &lt;typeinfo&gt;
  
  class Manager {
      //Vector holding pointers to any objects inherited from BaseClass
      vector&lt;BaseClass*&gt; baseClasses;
  
      //Template function that needs to add NEW object to baseClass vector
      //This I'm having problems with
      template&lt;class T&gt;
      BaseClass* Add() {
          BaseClass* baseClass = new T();
          baseClasses.push_back(baseClass);
          return baseClass;
      }
  
      //Template function that gets object from baseClass vector
      //This works fine
      template&lt;class T&gt;
      BaseClass* Get() {
          for (int i = 0; i &lt; baseClasses.size(); i++) {
              if (typeid(*baseClasses[i]) == typeid(T)) {
                  return baseClasses[i];
              }
          }
          return NULL;
      }
  };
  </code></pre>
  
  <p>For example, the user should do this when adding to or getting an object from the Manager's baseClass vector.  DerivedClass derives from BaseClass</p>
  
  <pre><code>Manager manager;
  //Add a new DerivedClass object to Manager's vector
  manager.Add&lt;DerivedClass&gt;();
  //Get a pointer to the DerivedClass object that was just added
  DerivedClass* derivedClass = (DerivedClass*)manager.Get&lt;DerivedClass&gt;();
  </code></pre>
  
  <p>My Get() function works fine.  What I need to know is, how can I get my Add() function to work?  Help would be greatly appreciated.</p>