-
October 28th, 2012, 08:38 PM
#1
Question about constructors in an array of objects.
What the best way to initialize a constructor in an array of objects?
Usually I declare an array of objects like so:
Is this the only way I know to initialize a constructor of an array:
Code:
for (int i = 0; i < 100; i++)
{
toyota[i] = Car(x, y);
}
Is this the proper way? Any answer to my question are welcomed.
Thank You
Benjamin Betancourt
-
October 29th, 2012, 04:24 AM
#2
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.
Code:
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)).
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:
Code:
#include <algorithm>
//...
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:eque, then this creates a container of Car, and uses Car(x,y) to initialize (using vector as an example).
Code:
#include <vector>
//...
std::vector<Car> CarVector(100, Car(x,y));
This basically is just like an array of Car, with each initialized to Car(x,y).
Regards,
Paul McKenzie
Last edited by Paul McKenzie; October 29th, 2012 at 04:34 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|