Generally, while writing the constructor function, I assume while initializing the members in the member-initialization list, the object inside the brackets are supposed to be the values we need the members to be initialized to. But, it doesn't seem to be the case. While initializing a vector, if I give an int instead of a vector, it is taking the input as size of the vector.
Look at the code below:
class A {
public:
vector<int> arr;
A() : arr({1,2,3}) {
}
};
int main() {
A r = A();
for(int i=0; i<3; i++){
cout<<r.arr[i]<<" ";
}
return 0;
}
For which the output is 1 2 3
which seems to be intuitive enough.
class A {
public:
vector<int> arr;
A() : arr(3) {
}
};
int main() {
A r = A();
for(int i=0; i<3; i++){
cout<<r.arr[i]<<" ";
}
return 0;
}
For which the output is 0 0 0
.
I understand the methods on how to initialize a vector, etc. My particular concern here is about the initializer list. In general, inside the brackets, we put the value of the member we're initializing. But for a vector, if we put vector
inside the initializer list, it's accepting the vector, and if we put a int
, it's accepting the int as size of the vector and initializing the vector with zeros. Please note that my concern here is the format of member initializer list in a class, and not on how to initialize a vector.
Why is the initializer accepting the size of the vector as input, and why are all the elements initialized to 0?
What is actually happening here, are there more cases like this for different datatypes, and how do I use this functionality to my advantage? Thank you.