views:

422

answers:

3

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???

+4  A: 

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.

GMan
you can use `_alloca()` to dynamically allocate variable amounts of memory on the stack...
Crashworks
That starts with an underscore, and that scares me. :) That's a C function, right? I don't know where it is in C++. That wouldn't be the "right" way anyway. (in the same way using new/delete aren't the right way)
GMan
@GMan - It's a nonstandard but widely provided C function.
Chris Lutz
It works the same way in C++ that it does in C; if there's a more standard way to tell the compiler to allocate N bytes on the stack where N is determined at runtime, I don't know what it is.
Crashworks
+2  A: 

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.

Tanuj
Didn't even notice that, good one. +1
GMan