More C++ Idioms/Named Constructor

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Named Constructor
[edit | edit source]

Intent[edit | edit source]

  • To have a readable and intuitive way of creating objects of a class
  • To impose certain constraints while creating objects of a class

Also Known As[edit | edit source]

Motivation[edit | edit source]

In C++, constructors are distinguished from each other only based on the type, the order and the number of parameters. Of course when a class has multiple constructors, each constructor has a different purpose. However, in C++ it is hard to capture that "semantic" difference in the interface of the class because all the constructors have the same name and only parameters can distinguish between them. Reading code with lots of constructor calls only differing in the type/order/number of parameters is quite unintuitive except for the original developer of the class. Named constructor idiom addresses the problem.

Solution and Sample Code[edit | edit source]

The named constructor idiom uses a set of static member functions with meaningful names to create objects instead of constructors. Constructors are either private or protected and clients have access only to the public static functions. The static functions are called "named constructors" as each unique way of creating an object has a different intuitive name. Consider the example below:

class Game
{
  public:
    static Game createSinglePlayerGame() { return Game(0); } // named constructor
    static Game createMultiPlayerGame() { return Game(1); }  // named constructor
  protected:
    Game (int game_type);
};
int main(void)
{
   Game g1 = Game::createSinglePlayerGame(); // Using named constructor
   Game g2 = Game(1); // multiplayer game; without named constructor (does not compile)
}

Without using the named constructor idiom in the class above, it is difficult to convey the meaning of what Game(1) and Game(0) means. The idiom makes it loud and clear! Additionally, it is possible to put certain constraints on the object creation process using this idiom. For example, named constructors could always create an object dynamically using new. In such a case, Resource Return idiom could be helpful.

Known Uses[edit | edit source]

Related Idioms[edit | edit source]

Resource Return

References[edit | edit source]

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8