Split
Split

Reputation: 299

How would I create this array of object using pointer

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?

Upvotes: 0

Views: 62

Answers (3)

kfsone
kfsone

Reputation: 24249

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

Upvotes: 1

Dineshkumar
Dineshkumar

Reputation: 4245

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

Upvotes: 0

David G
David G

Reputation: 96800

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

Upvotes: 3

Related Questions