Named constructor idiom and new operator
<p>I use the named constructor idiom to create objects, because I have lots of calls with identical parameters but the object shall be created differently.</p>

<p>The <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8" rel="nofollow">C++ FAQ</a> tell us how to do this. It also tells us how to force objects being heap allocated. Yet it really fails to tell us how to use the named constructor idiom with the new operator.</p>

<p>Because new requires a constructor to be called we cannot directly call named constructors. So I found two workarounds to this problem:</p>

<p>I create an additional copy constructor and hope that optimizing compilers won't create a temporary object.</p>

<pre><code>class point_t {
    int X,Y;
    point_t(int x, int y) : X(x), Y(y) { }
  public:
    point_t(const point_t &amp;x) : X(x.X), Y(x.Y) { }
    static point_t carthesian(int x, int y) { return point_t(x,y); }
    static point_t polar(float radius, float angle) {
      return point_t(radius*std::cos(angle), radius*std::sin(angle));
    }

    void add(int x, int y) { X += x; Y += y; }
};



int main(int argc, char **argv) {
  /* XXX: hope that compiler doesn't create a temporary */
  point_t *x = new point_t(point_t::carthesian(1,2));
  x-&gt;add(1,2);
}
</code></pre>

<p>The other version is to create separate named constructors. Because function overloading doesn't work on return type I use two different names, which is ugly.</p>

<pre><code>class point_t {
    int X,Y;
    point_t(int x, int y) : X(x), Y(y) { }
  public:
    /* XXX: function overloading doesn't work on return types */
    static point_t carthesian(int x, int y) { return point_t(x,y); }
    static point_t *carthesian_heap(int x, int y) { return new point_t(x,y); }
    void add(int x, int y) { X += x; Y += y; }
};

int main(int argc, char **argv) {
  point_t *x = point_t::carthesian_heap(1,2);
  x-&gt;add(1,2);
}
</code></pre>

<p>Is there a prettier version that is equal to the example code? </p>
