title: How to implement the factory method pattern in C++ correctly
body: <p>There's this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don't know how to do it, even though it sounds simple:</p>
  
  <h1><strong>How do I implement Factory Method in C++ correctly?</strong></h1>
  
  <p>Goal: to make it possible to allow the client to instantiate some object using factory methods instead of the object's constructors, without unacceptable consequences and a performance hit. </p>
  
  <p>By "Factory method pattern", I mean both static factory methods inside an object or methods defined in another class, or global functions. Just generally "the concept of redirecting the normal way of instantiation of class X to anywhere else than the constructor".</p>
  
  <p>Let me skim through some possible answers which I have thought of.</p>
  
  <hr>
  
  <h2>0) Don't make factories, make constructors.</h2>
  
  <p>This sounds nice (and indeed often the best solution), but is not a general remedy. First of all, there are cases when object construction is a task complex enough to justify its extraction to another class. But even putting that fact aside, even for simple objects using just constructors often won't do.</p>
  
  <p>The simplest example I know is a 2-D Vector class. So simple, yet tricky. I want to be able to construct it both from both Cartesian and polar coordinates. Obviously, I cannot do:</p>
  
  <pre><code>struct Vec2 {
      Vec2(float x, float y);
      Vec2(float angle, float magnitude); // not a valid overload!
      // ...
  };
  </code></pre>
  
  <p>My natural way of thinking is then:</p>
  
  <pre><code>struct Vec2 {
      static Vec2 fromLinear(float x, float y);
      static Vec2 fromPolar(float angle, float magnitude);
      // ...
  };
  </code></pre>
  
  <p>Which, instead of constructors, leads me to usage of static factory methods... which essentially means that I'm implementing the factory pattern, in some way ("the class becomes its own factory"). This looks nice (and would suit this particular case), but fails in some cases, which I'm going to describe in point 2. Do read on.</p>
  
  <p><em>another case: trying to overload by two opaque typedefs of some API (such as GUIDs of unrelated domains, or a GUID and a bitfield), types semantically totally different (so - in theory - valid overloads) but which actually turn out to be the same thing - like unsigned ints or void pointers.</em></p>
  
  <hr>
  
  <h2>1) The Java Way</h2>
  
  <p>Java has it simple, as we only have dynamic-allocated objects. Making a factory is as trivial as:</p>
  
  <pre><code>class FooFactory {
      public Foo createFooInSomeWay() {
          // can be a static method as well,
          //  if we don't need the factory to provide its own object semantics
          //  and just serve as a group of methods
          return new Foo(some, args);
      }
  }
  </code></pre>
  
  <p>In C++, this translates to:</p>
  
  <pre><code>class FooFactory {
  public:
      Foo* createFooInSomeWay() {
          return new Foo(some, args);
      }
  };
  </code></pre>
  
  <p>Cool? Often, indeed. But then- this forces the user to only use dynamic allocation. Static allocation is what makes C++ complex, but is also what often makes it powerful. Also, I believe that there exist some targets (keyword: embedded) which don't allow for dynamic allocation. And that doesn't imply that the users of those platforms like to write clean OOP.</p>
  
  <p>Anyway, philosophy aside: In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.</p>
  
  <hr>
  
  <h2>2) Return-by-value</h2>
  
  <p>OK, so we know that 1) is cool when we want dynamic allocation. Why won't we add static allocation on top of that?</p>
  
  <pre><code>class FooFactory {
  public:
      Foo* createFooInSomeWay() {
          return new Foo(some, args);
      }
      Foo createFooInSomeWay() {
          return Foo(some, args);
      }
  };
  </code></pre>
  
  <p>What? We can't overload by the return type? Oh, of course we can't. So let's change the method names to reflect that. And yes, I've written the invalid code example above just to stress how much I dislike the need to change the method name, for example because we cannot implement a language-agnostic factory design properly now, since we have to change names - and every user of this code will need to remember that difference of the implementation from the specification.</p>
  
  <pre><code>class FooFactory {
  public:
      Foo* createDynamicFooInSomeWay() {
          return new Foo(some, args);
      }
      Foo createFooObjectInSomeWay() {
          return Foo(some, args);
      }
  };
  </code></pre>
  
  <p>OK... there we have it. It's ugly, as we need to change the method name. It's imperfect, since we need to write the same code twice. But once done, it works. Right?</p>
  
  <p>Well, usually. But sometimes it does not. When creating Foo, we actually depend on the compiler to do the return value optimisation for us, because the C++ standard is benevolent enough for the compiler vendors not to specify when will the object created in-place and when will it be copied when returning a temporary object by value in C++. So if Foo is expensive to copy, this approach is risky.</p>
  
  <p>And what if Foo is not copiable at all? Well, doh. (<em>Note that in C++17 with guaranteed copy elision, not-being-copiable is no problem anymore for the code above</em>)</p>
  
  <p>Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.</p>
  
  <hr>
  
  <h2>3) Two-phase construction</h2>
  
  <p>Another thing that someone would probably come up with is separating the issue of object allocation and its initialisation. This usually results in code like this:</p>
  
  <pre><code>class Foo {
  public:
      Foo() {
          // empty or almost empty
      }
      // ...
  };
  
  class FooFactory {
  public:
      void createFooInSomeWay(Foo&amp; foo, some, args);
  };
  
  void clientCode() {
      Foo staticFoo;
      auto_ptr&lt;Foo&gt; dynamicFoo = new Foo();
      FooFactory factory;
      factory.createFooInSomeWay(&amp;staticFoo);
      factory.createFooInSomeWay(&amp;dynamicFoo.get());
      // ...
  }
  </code></pre>
  
  <p>One may think it works like a charm. The only price we pay for in our code...</p>
  
  <p>Since I've written all of this and left this as the last, I must dislike it too. :) Why?</p>
  
  <p>First of all... I sincerely dislike the concept of two-phase construction and I feel guilty when I use it. If I design my objects with the assertion that "if it exists, it is in valid state", I feel that my code is safer and less error-prone. I like it that way.</p>
  
  <p>Having to drop that convention AND changing the design of my object just for the purpose of making factory of it is.. well,  unwieldy.</p>
  
  <p>I know that the above won't convince many people, so let's me give some more solid arguments. Using two-phase construction, you cannot:</p>
  
  <ul>
  <li>initialise <code>const</code> or reference member variables,</li>
  <li>pass arguments to base class constructors and member object constructors.</li>
  </ul>
  
  <p>And probably there could be some more drawbacks which I can't think of right now, and I don't even feel particularly obliged to since the above bullet points convince me already.</p>
  
  <p>So: not even close to a good general solution for implementing a factory.</p>
  
  <hr>
  
  <h2>Conclusions:</h2>
  
  <p>We want to have a way of object instantiation which would: </p>
  
  <ul>
  <li>allow for uniform instantiation regardless of allocation,</li>
  <li>give different, meaningful names to construction methods (thus not relying on by-argument overloading),</li>
  <li>not introduce a significant performance hit and, preferably, a significant code bloat hit, especially at client side,</li>
  <li>be general, as in: possible to be introduced for any class.</li>
  </ul>
  
  <p>I believe I have proven that the ways I have mentioned don't fulfil those requirements.</p>
  
  <p>Any hints? Please provide me with a solution, I don't want to think that this language won't allow me to properly implement such a trivial concept.</p>