コンストラクターのメンバー初期化子リストを使用します。
class Super {
public:
int x, y;
Super() : x(100), y(100) // initialize x and y to 100
{
// that was assignment, not initialization
// x = y = 100;
}
};
class Sub : public Super {
public:
float z;
Sub() : z(2.5) { }
};
基本クラスのデフォルトコンストラクターを明示的に呼び出す必要はありません。派生クラスのコンストラクターが実行される前に自動的に呼び出されます。
一方、基本クラスをパラメーターを使用して構築する場合(そのようなコンストラクターが存在する場合)、それ を呼び出す必要があります。
class Super {
public:
int x, y;
explicit Super(int i) : x(i), y(i) // initialize x and y to i
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(100), z(2.5) { }
};
さらに、引数なしで呼び出すことができるコンストラクターもデフォルトのコンストラクターです。だからあなたはこれを行うことができます:
class Super {
public:
int x, y;
explicit Super(int i = 100) : x(i), y(i)
{ }
};
class Sub : public Super {
public:
float z;
Sub() : Super(42), z(2.5) { }
};
class AnotherSub : public {
public:
AnotherSub() { }
// this constructor could be even left out completely, the compiler generated
// one will do the right thing
};
また、基本メンバーをデフォルト値で初期化したくない場合にのみ、明示的に呼び出してください。
お役に立てば幸いです。