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?

2
  • 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?) Commented Jun 2, 2013 at 2:45
  • Possible duplicate: stackoverflow.com/questions/4754763/… Commented Jun 2, 2013 at 2:50

3 Answers 3

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(...) };
Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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
     ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.