title: C++ factory method pattern for abstract class
body: <p>I have to implement a factory method pattern in C++. The class (C) that is to be "assembled" by the factory is abstract and is inherited by some other class (D). So I don't want C to have a constructor. But to create an instance of D, C has to have at least a protected constructor. But then someone might derive from C and create an instance of C in this way. I don't want this to happen. So I created a protected constructor that takes a pointer to a C object for derived classes to use, code is below. The question is whether that is the correct way of dealing with this issue.</p>
  
  <pre><code>class C {
  private:
   C() {}
  protected:
   C(const C* c) {}
  friend class CFactory
  };
  
  class D: public C
  {
  private:
   D(const C* c): C(c) {}
  friend class CFactory;
  };
  
  class CFactory
  {
  public:
   static C* createC() {
    C* ptr = new C();
    ptr = new D(ptr); // There is garbage collection on the project, so no memory leak.
   }
  };
  </code></pre>