C++ array of objects question

dimagog

Junior Member
Feb 18, 2002
9
0
0
I have a class and I want to create an array of objects of this class.
I have a constructor and I have no trouble initializing a single object,
but when it comes to an array the compiler starts complaining.

I don't have a book with me right now, so I got away by creating an array of pointers to the object and then initializing these pointers in a loop.

What's the right way to accomplish this task?

Thank you in advance.
 

Elledan

Banned
Jul 24, 2000
8,880
0
0
How do you initialize your class? It should be possible to create an infinite number of objects using a class.
 

dimagog

Junior Member
Feb 18, 2002
9
0
0
Say I have class item

I can initialize one object like this:

item new_item(x, y, z) // x, y, z being different parameters for constructor.

Now I'm trying to create a dinamic array of items:

item* bag_of_items
bag_of_items = new item[5] // there is a number in brackets after item (it may not come out)

And here is the first problem: where do the parameters for the constructor go?
is it like item* bag_of_items(x, y, z) ?
Or does it go somewhere where the array is initialized?

Or do I have to add some special constuctor for the class to handle dinamic array creation?

 

Elledan

Banned
Jul 24, 2000
8,880
0
0
You put the newly created objects in the array. First you create the array, then you add the objects into the array one by one:

If we use your class 'item'

item array[11]; // an array for 12 objects of the type 'item'
array[0] = item new_item_1(x, y, z) // first item added
array[1] = item new_item_2(x, y, z) // second item added

//.... etc.

Hope this helps.
 

HigherGround

Golden Member
Jan 9, 2000
1,827
0
0
ANSI C++ does not allow class array initializers with non default constructor,
although some compilers ( some versions of GNU gcc ) allow that feature via
their own extensions, anyway that will prevent you from declaring array instances
that look like this ...

struct C { C(int i) : c(i) {} int c; };
C ic[6](0);

however, you can still do any of the following ( using the same class C )

C ic[] = { 0, 0, 0, 0, 0, 0 }; // array of 6 C instances with all C.c members initialized to 0
C ic[] = { C(0), C(0), C(0) }; // ditto for 3 C instances
C *ic[] = { new C(0), new C(0) };
C* ic[2];
for(int j=0; j<2; j++)
ic[j] = new C(0);



<<
item array[11]; // an array for 12 objects of the type 'item'
array[0] = item new_item_1(x, y, z) // first item added
array[1] = item new_item_2(x, y, z) // second item added
>>



if he does not have a default constructor, the instantiation of item array[11]; will fail,
on top of that you'd be duplicating each element ( @ array creation and @ instance assigments ), plus
array[0] = item new_item_1(x, y, z); should really be array[0] = item(x, y, z);


edit: tags