メンバー オブジェクトがコンストラクターの初期化リストに表示されdata
ない場合data
は、既定のコンストラクターによって構築されます。
コンストラクターの初期化リストにある場合は、単純にdata
指定された値に初期化されます。これは、作成するためのコンストラクター呼び出しがないことを意味しdata
ますか? その場合、新しいオブジェクトはどのようにdata
構築されますか?
メンバー オブジェクトがコンストラクターの初期化リストに表示されdata
ない場合data
は、既定のコンストラクターによって構築されます。
コンストラクターの初期化リストにある場合は、単純にdata
指定された値に初期化されます。これは、作成するためのコンストラクター呼び出しがないことを意味しdata
ますか? その場合、新しいオブジェクトはどのようにdata
構築されますか?
If data appears in the constructor's initialization list, then it is simply initialized to the given value.
No, it is initialised using whatever arguments are supplied. If it has a class type, then the arguments are passed to a suitable constructor.
Does this imply that there is no constructor call for creating data?
No. If it has a class type, then initialisation is done by calling a constructor.
When you're initializating data
in the constructor's initialization list, its parametrized constructor is called.
Example:
#include <iostream>
#include <string>
class Data {
public:
Data(int firstArg, std::string mSecondArg)
{
std::cout<<"parameterized constructor called"<<std::endl;
}
};
class SomeClass {
public:
SomeClass(int firstArg, std::string secondArg) : data(firstArg, secondArg) {}
private:
Data data;
};
int main(int argc, char** argv) {
SomeClass someObj = new SomeClass(0, new std::string("empty"));
return 0;
}
With this code you will get output
parameterized constructor called