0

Basically I want to create an array of objects with a size which is passed through from one class to another i.e.

Object * ArrayOfObjects = new Object[Size];

Whilst that creates an array successfully, it doesnt allow me to use constructors.

How can I create an array of my objects then define each object in the array?

Split
  • 259
  • 2
  • 5
  • 11
  • 1
    You have to loop through the array and create each object. Your statement just allocates memory for an array, it doesn't initialize the objects. (Think, what if Object was an abstract class?) – GJK Jun 02 '13 at 02:45
  • Possible duplicate: http://stackoverflow.com/questions/4754763/c-object-array-initialization-without-default-constructor – jrd1 Jun 02 '13 at 02:50

3 Answers3

3

Once you allocate memory for the array you can then assign to it by looping:

for (int i = 0; i < Size; ++i)
{
    ArrayOfObjects[i] = Object( /* call the constructor */ );
}

Or you can use a vector to do the same but with more ease of use:

std::vector<Object> ArrayOfObjects = { Object(...), Object(...) };
David G
  • 94,763
  • 41
  • 167
  • 253
1

What you're asking may not actually be the best thing to do - which would be to use something like std::vector or something, but under the hood what they're going to do is what your question asks about anyway.

Then you can either assign or placement new each entry:

for (size_t i = 0; i < Size; ++i)
{
     // Option 1: create a temporary Object and copy it.
     ArrayOfObjects[i] = Object(arg1, arg2, arg3);
     // Option 2: use "placement new" to call the instructor on the memory.
     new (ArrayOfObjects[i]) Object(arg1, arg2, arg3);
}
kfsone
  • 23,617
  • 2
  • 42
  • 74
0

Once you allot memory, as you did. You initialize each object by traversing the array of objects and call its constructor.

#include<iostream>
using namespace std;
class Obj
{
    public:
    Obj(){}
    Obj(int i) : val(i)
    {
        cout<<"Initialized"<<endl;
    }
    int val;
};
int allot(int size)
{

    Obj *x= new Obj[size];
    for(int i=0;i<10;i++)
        x[i]=Obj(i);

     //process as you need
     ...
}
Dineshkumar
  • 4,165
  • 5
  • 29
  • 43