Reputation: 3848
Which is the appropriate way (if any) to list initialize an empty vector on the class ctor assuming?:
class Temp {
private:
int vals;
vector<int> A;
public:
Temp(int x);
};
All of these seem to work, but is it even necessary to do #1 or #2, or is declaration enough?:
1: Calling vector constructor explicitly
Temp::Temp(int x):vals(x), A() { }
2: Using vector list initialization within class ctor list initialization
Temp::Temp(int x):vals(x), A{} { }
3: Excluding from class ctor list initialization (declaration only)
Temp::Temp(int x):vals(x) { }
There doesnt appear to be any value from including the vector member in the class ctor initialization list since its default constructor is called when we declare it and returns an empty vector.
Upvotes: 7
Views: 14049
Reputation: 17483
Which is the appropriate way (if any) to list initialize an empty vector on the class ctor assuming?
They are all valid.
It is mostly a matter of style. If you do care about setting all class members in the constructor member initializer list explicitly, then you might include initialization of A
for consistency, otherwise, std::vector
default constructor is called automatically.
Usually, only the members which require some kind of non-default initialization go to the member initializer list:
Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for anonymous unions or variant members that do not have a member initializer.
Upvotes: 5