Declare an array at .h and create at .cpp


I'm a little losted...

I want to declare an array of objects at .h file (to say my class that are private). And later, I want to create it :

at .h
a_object *obs[];

at .cpp ???

void the_method_where_I_want_to_create_it.
{
>>>>>> obs=new a_object[20] ?????
But if a_object has an argument at constructor ????
}

If I declare at h.file :
a_object *obs[const 20];
later at .cpp I can do:
obs[0] = new a_object(argument);

I want to create 20 obs into cpp. How ?
I don't know how to do it.
Thanks



Last edited on
Header file:
extern std::vector<a_object> objects;

Implementation file:
1
2
3
4
5
6
7
void the_method_where_I_want_to_create_it()
{
  for (int i=0;i<20;i++)
  {
    objects.push_back(a_objects(parameters,here));
  }
}


Note that vectors store copies of the objects you pass to push_back.
When the objects is not copyable (or if it is not desirable), you can use ptr_vector:
1
2
extern boost::ptr_vector<a_object> objects;
//doesn't need to be the boost one, there are many implementations of ptr_vector 

And the other line changes to:
objects.push_back(new a_object(parameters,here));

It would probably be better to create a class that manages the set of objects instead of simply having a global, generic container. Depends on your situation, though.
Thanks
And, summarizing, is not posible to declare an array of objects (with or not with parameters at constructor) at h. file and give the dimension later ?
if you stored a pointer and allocated the array dynamically then it is
Some example ?
I have difficulties to do so when the class contructor are waiting for parameters...
So my_array = new class[5] ????? does not work..
Yes, you cannot dynamically allocate an array of objects and call any constructor other than the default one.

std::vector<> overcomes this limitation.
Topic archived. No new replies allowed.