「More C++ Idioms/名前付きコンストラクタ(Named Constructor)」の版間の差分

削除された内容 追加された内容
編集の要約なし
1 行
=<center>Named Constructor</center>=
== Intent ===
* 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 ===
 
=== Motivation ===
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 ===
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:
 
<source lang="cpp">
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)
}
</source>
 
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, [[More C++ Idioms/Resource Return|Resource Return]] idiom could be helpful.
== Known Uses ==
 
=== RelatedKnown IdiomsUses ===
 
=== ReferencesRelated Idioms ===
[[More C++ Idioms/Resource Return|Resource Return]]
 
=== References ===
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8
[[Category:{{BASEPAGENAME}}|{{SUBPAGENAME}}]]