I want to create in C++ an array of Objects without using STL.
How can I do this?
How could I create array of Object2, which has no argumentless constructor
If the type in question has an no arguments constructor, use new[]
:
Object2* newArray = new Object2[numberOfObjects];
don't forget to call delete[]
when you no longer need the array:
delete[] newArray;
If it doesn't have such a constructor use operator new
to allocate memory, then call constructors in-place:
//do for each object
::new( addressOfObject ) Object2( parameters );
Again, don't forget to deallocate the array when you no longer need it.
The obvious question is why you don't want to use the STL.
Assuming you have a reason, you would create an array of objects with something like Obj * op = new Obj[4];
. Just remember to get rid of it with delete [] op;
.
You can't do that with an object with no constructor that doesn't take arguments. In that case, I think the best you could do is allocate some memory and use placement new. It isn't as straightforward as the other methods.
Object2 *myArray[42];
for (int i = 0; i < 42; i++)
{
myArray[i] = new Object2(param1, param2, ...);
}
Later on you will have to walk through the array and deallocate each member individually:
for (int j = 0; j < 42; j++)
{
delete myArray[j];
}