0

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?

2
  • 4
    To encourage you to use std::vector ;) Commented Apr 26, 2012 at 22:02
  • To turn the question around, what would be an alternative? If declaring an array of objects didn't instantiate them then how would you instantiate them manually? Would you need to use placement new to do it? Doesn't it seem like that would be horribly error prone? Given that the objects need to be instantiated before you use them then doing it automatically seems like the best solution to me. As recommended above, if you prefer to do it as you need them then use a container like vector rather than a static array. Commented Apr 26, 2012 at 22:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And you can use vector::reserve to reserve capacity without constructing anything.
Though, of course, you don't have to create a vector empty -- you can pass an initial size to the constructor if you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.