Re: Question about constructors in an array of objects.
Originally Posted by crazyben21
What the best way to initialize a constructor in an array of objects?
Usually I declare an array of objects like so:
That one line already constructs the objects. Once an array of type T is declared, all of the elements in the array are constructed using the default constructor. So there is no way to construct an array of objects any differently, since declaring automatically constructs objects. Your question then becomes a moot point.
for (int i = 0; i < 100; i++)
toyota[i] = Car(x, y);
That code does not construct Car objects on the left side of the equal sign. All you're doing there is assigning to an existing object (toyota[ i ]) the value of a temporary object (Cars(x,y)).
Is this the proper way?
If you're asking if this is the "proper" way to assign to an object, then does that way work? Then it is the "proper" way.
Just to let you know, this does the same thing:
std::fill(toyota, toyota + 100, Car(x,y));
No loop needed.
Now if you're talking about using a container such as std::vector or std::deque, then this creates a container of Car, and uses Car(x,y) to initialize (using vector as an example).