title: C++ Automatic instantiation of derived classes
body: <p>I have an abstract base class called <code>Base</code> that other programmers are to write implementations for. In some other part of the application, I want to catch all implementations that have been written and construct a single instance of each. If this could be done with no additional instructions to others beyond "implement Base", that would be beautiful. However, the code I have below, requires that each implementation register itself. It also doesn't work.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class Base;
  
  std::vector&lt;Base*&gt;* registrationList = new std::vector&lt;Base*&gt;;
  
  class Base {
  public:
     Base(){}
     virtual void execute() = 0;
  };
  
  class ImplementationOne: public Base {
  public:
     ImplementationOne(){registrationList-&gt;push_back(this);}
     void execute(){std::cout &lt;&lt; "Implementation One." &lt;&lt; std::endl;}
     static int ID;
  };
  
  class ImplementationTwo: public Base {
  public:
     ImplementationTwo(){registrationList-&gt;push_back(this);}
     void execute(){std::cout &lt;&lt; "Implementation Two." &lt;&lt; std::endl;}
     static int ID;
  };
  
  int main(int argc, const char * argv[]){
     std::cout &lt;&lt; "Registration List size: " &lt;&lt; registrationList-&gt;size() &lt;&lt; std::endl;
     for(auto it = registrationList-&gt;begin() ; it != registrationList-&gt;end() ; ++it){
        (dynamic_cast&lt;Base*&gt;(*it))-&gt;execute();
     }
     return 0;
  }
  </code></pre>
  
  <p>I get an output of: <code>Registration List size: 0</code>, so it is clear that the implementations were never instantiated. It is probably obvious that this wouldn't happen, but I am a beginner and this is the best I could come up with. I assumed that <code>static int ID;</code> would force instantiation of each implementation, which would then register themselves. I can see <code>static</code> does not result in instantiation. I leave it in my code here since it shows my intent.</p>
  
  <p>What can I do to get automatic instantiation of each implementation? Is it possible?</p>