0

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.

madhan01
  • 117
  • 5
  • `std::vector` has a ctor that accepts the size for the vector. You passed 3. – wohlstad Nov 04 '22 at 13:38
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. See [this](https://stackoverflow.com/a/10559309/12002570). – Jason Nov 04 '22 at 13:40
  • 1
    Perhaps [this `std::vector` constructor reference](https://en.cppreference.com/w/cpp/container/vector/vector) can help you? The alternative used in your second example is number 4 in the reference. It sets the size of the vector, and makes sure all elements are default-initialized (which for integers is the value `0`). – Some programmer dude Nov 04 '22 at 13:40
  • Question title is misleading. This has nothing to do with arrays. – paddy Nov 04 '22 at 13:41
  • 1
    @Someprogrammerdude [value-initialized](https://en.cppreference.com/w/cpp/named_req/DefaultInsertable). Why that is then called "*default* insertion", I do not know. – Quentin Nov 04 '22 at 13:45

0 Answers0