「More C++ Idioms/仮想コンストラクタ(Virtual Constructor)」の版間の差分

削除された内容 追加された内容
編集の要約なし
6 行
 
=== Motivation ===
Uses of calling member functions in a class hierarchy polymorphically are well known in the object-oriented programming community. It is a way of implementing the "'''is-a"''' (or more practically, "'''behaves-as-a"''') relationship. Sometimes it is useful to call life-cycle management (creation, copy, and destruction) functions of a class hierarchy polymorphically.
 
C++ natively supports polymorphic destruction of objects using a virtual destructor. An equivalent support for cration and coping of objects is missing. In C++, creation of object(s) always requires its type to be known at compile-time. The Virtual Constructor idiom allows polymorphic creation of and coping of objects in C++.
44 行
The Manager class implements the two pure virtual functions and uses the type name (Manager) to create them. The function duplicate shows how virtual constructor idiom is used. It does not really know what it is duplicating. It only knows that it is cloning an Employee. The responsibility of creating the right instance is deligated to the derived classes. The duplicate function is therefore closed for modifications even though the class hierarchy rooted at Employee gets more sub-classes added in the future.
 
The return type of the clone and create member functions of the Manager class is not Employee but the class itself. C++ allows this flexibility in types where the return type of the over-ridden function can be a derived type of that of the function in the base class. This language feature is known as '''co-variant return types.'''
 
To handle resource ownership properly, the [[More C++ Idioms/Resource Return|Resource Return]] idiom should be employed for the return types of clone() and create() functions as they are factory functions. If used, the return types are no longer covariant return types and program should fail to compile. In such a case, the virtual constructor functions in the derived class should return the exact type as in the parent class.