title: C++ - Superclass constructor producing an instance of a subclass
body: <p>I have two classes, one of which is a subclass of another, and differs only by the fact that it contains an additional member variable to its parent. I am not using the default constructor, passing in a reference to a single object as the constructors parameter. What I would like is for the constructor of the parent to examine this object, and then determine whether to construct an instance of the parent class (in most cases) or the subclass (in a few specialised cases).</p>
  
  <pre><code>class Superclass 
  { 
      public: 
          Foo foo;
  
          Superclass(MyObject* object) 
          { 
              foo = object-&gt;GetFoo();
  
              if(object-&gt;CreateSubclass())
              {
                  //Create Subclass
              }
              else
              {
                  //Create Superclass
              }
          } 
  }; 
  
  class Subclass : public Superclass 
  { 
      public: 
          Barr barr;
  
          Subclass(MyObject* object)
          { 
              barr = object-&gt;GetBarr();
          } 
  };
  </code></pre>
  
  <p>I'm aware of the factory design pattern, but don't want to have to have a factory object just for this. I'd rather duplicate the Superclass initialisation stuff into the Subclass (which seems bad) and then examine the object at each of the points where a Superclass is created and then call the appropriate constructor:</p>
  
  <pre><code>Superclass* class;
  if(object-&gt;CreateSubclass())
  {
      class = new Subclass(obj);
  }
  else
  {
      class = new Superclass(obj);
  }
  </code></pre>
  
  <p>Is this sort of thing possible, and if so how would I go about calling the subclasses constructor from Superclass constructor? I've tried making a call to <code>Subclass(object)</code>, but I run into issues with both Superclass and Subclass needing to be defined before the other.</p>
  
  <p>Thanks for any advice you can provide.</p>