Member objects of classes without default constructors
Const members
Reference members
Assume that T2 in the following does not have default constructor
Class MyClass
{
string name;
const int i;
T1& obj1;
T2 obj2;
MyClass(){}; //wrong - i, T1, T2 require initialization in the initializer list
}
Adding following constructor(and corresponding declaration in the class declaration) would fix the issue
MyClass::MyClass(const int _i, T1& _obj1, T2 _obj2):_i(i), obj1(_obj1), obj2(_obj2){}
Ref. C++ Language, The (3rd Edition) by Bjarne Stroustrup , page 248.
Const members
Reference members
Assume that T2 in the following does not have default constructor
Class MyClass
{
string name;
const int i;
T1& obj1;
T2 obj2;
MyClass(){}; //wrong - i, T1, T2 require initialization in the initializer list
}
Adding following constructor(and corresponding declaration in the class declaration) would fix the issue
MyClass::MyClass(const int _i, T1& _obj1, T2 _obj2):_i(i), obj1(_obj1), obj2(_obj2){}
Ref. C++ Language, The (3rd Edition) by Bjarne Stroustrup , page 248.
No comments:
Post a Comment