I was wondering if it was possible to create an array of objects when the object needs things passed into it for the constructor. I want something like this:
MyClass *myVar;
myVar = new MyClass[num]; // I would like to specify the array size after declaration
int i = 0;
for(i = 0;i < num;i++)
myVar[i] = new MyClass(0,0); // I would also like to populate the array with new objects
I know that this works:
MyClass *myVar;
myVar = new MyClass[num];
but this only works when the constructor has nothing passed into it. Is what I am trying to do possible? If so, how do I do it?
EDIT: I found out how to do it with using arrays. Here is how I did it:
MyClass **myVar;
myVar = new MyClass *[num];
for(i = 0;i < num;i++)
myVar[0] = new MyClass(0,0);
I would use vectors and such but my teacher has told us to use basic arrays whenever possible. The above solution I actually got from some code my teacher wrote. Thank you all for your help!
Actually in this form you cannot invoke constructor which takes parameter(s). It is not allowed by the language specification.
However, if you use
std::vector, which I recommend you to use, then you can create a vector calling non-default constructor as:It creates a vector of
numelements, each element is created by calling copy-constructor of the class, passingMyClass(10,20)as argument to it.The vector is also good because now you dont need to manage memory yourself. Neither manual allocation, nor manual deallocation. Plus, you can know the number of elements by calling
arr.size()anytime. You always know how many elements the vector contains. You can also add elements anytime, just by calling.push_back()member function as:And now you can access elements, just like you access array, i.e by using index:
Additionally, you can use iterators which facilitate idiomatic programming, enabling you to use various algorithmic functions from
<algorithm>header as:where
fis function which takes one argument of typeMyClass&(orMyClass const &) depending on what you want to do inf.In C++11, you can use lambda as: