Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of objects of myarray on stack and how can you create an array of objects on heap???
Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of objects of myarray on stack and how can you create an array of objects on heap???
You can create an array of objects on the stack via:
myarray stackArray[100]; // 100 objects
And on the heap:
myarray *heapArray = new myarray[100];
delete [] heapArray; // when you're done
But it's best not to do that yourself, and use a std::vector:
#include <vector>
std::vector<myarray> bestArray(100);
A vector is a dynamic array, which (by default) allocates elements from the heap.*
Do you really want an array of myarray
objects, or an array if ints instead?
int stackArray[100]; // 100 ints
std::vector<int> bestArray(100);
You can read a tutorial on array's here: http://www.cplusplus.com/doc/tutorial/arrays/
Because your class has no default constructor, to create it on the stack you need to let the compiler know what to pass into the constructor:
myarray stackArray[3] = {1, 2, 3};
Or with a vector:
std::vector<myarray> bestArray;
bestArray.push_back(1);
bestArray.push_back(2);
bestArray.push_back(3);
You cannot do it with a single new command. Of course, you could always give it a default constructor:
class myarray
{
int i;
public:
myarray(int a = 0) : i(a){ }
}
* If you want dynamic allocation from the stack, you'd need to define a max size (stack storage is known ahead of time), and then give vector a new allocator so it uses the stack instead.
If you create an array of objects of class myarray ( either on stack or on heap) you would have to define a default constructor.
There is no way to pass arguments to the constructor when creating an array of objects.