• Announcements

Archived

This topic is now archived and is closed to further replies.

how to create array of object in c++?

Recommended Posts

wah_on_2    122
Like that: class A{ int num; //data member A(int i) //constructor { num = i; } } how to create array of A object? Thanks

Share on other sites
wah_on_2    122
O...i tried myself. I can write that:

A aobj[2] = {A(10), A(20)};

but if i want to use pointer, how to do?

Share on other sites
krez    443
A* objArray = new A[NumObjects];

note that only the default constructor is called for these new objects.

--- krez (krezisback@aol.com)

Edited by - krez on January 3, 2002 2:17:52 PM

Share on other sites
wah_on_2    122
Yes, but if i have no default constructor, how can i do?

my one and only one constructor is
A(10){
.....
}

Share on other sites
krez    443
this is probably not the "right" way to do it, but you could have a default constructor which does nothing, and a separate Init(int) member function that you can use to set up the objects.

--- krez (krezisback@aol.com)

Share on other sites
wah_on_2    122
ic. I know your method can achieve the goal. Is it the one and only one solution?

Because my teacher/book teach that the function of constructor is used to initailization.

Share on other sites
krez    443
yah i know... i was just trying to give you a way to do it
i''m sure there are other [more elegant] ways, but none spring to mind.

--- krez (krezisback@aol.com)

Share on other sites
xgalaxy    124
Actually, I had a similar problem a few days ago. I was told to do something like:

  CBlockData* blockObjects = new CBlockData* [numOfType];

But I instead did something different. If you remember, you can treat arrays similar to pointers in some respects.. here is my solution that is working for me anyways:

  // An array of pointers, nullify it at firstCBlockData** blockObjects = 0;// For each object...for(int i = 0; i < numOfType; i++) // ... Assign it blockObjects[i] = getBlockObject(blockIndex[i]);

the call to getBlockObject is returning the address of the object and assigning it to blockObjects.

Edited by - xgalaxy on January 4, 2002 12:59:28 PM