Why is C++ created in such a way, that if you have a class A and you declare an array of type A, then the whole array gets filled with objects instantiated with the default constructor of the class?
1 Answer
Because when you create an array of a given size, each element of the array has to be valid as soon as it's created.
If you want a different behavior you can use vector and push_back. A vector is created empty; when you want to add a new element, push_back will take an object that is created any way you want and make a copy of it in the vector.
2 Comments
Matthew Flaschen
And you can use
vector::reserve to reserve capacity without constructing anything.Jerry Coffin
Though, of course, you don't have to create a vector empty -- you can pass an initial size to the constructor if you want.
std::vector;)