Archived

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

oxygen_728

C++ - How do I have a variable sized array of objects...

Recommended Posts

oxygen_728    122
I want to prototype an array of CBALL objects as: class CBuilding{ ... CBall* Balls ... or CBall** Balls (or however it is done.) ... } Then, in my CBuilding class''s constructor... Balls = Array of Balls of size MAX_BALLS_IN_BUILDING MAX_BALLS_IN_BUILDING is #define''d as a certain integer. ---- My primary concern... What is the proper way to put a new instance of a CBALL object in each position in the array? Thank you for the help!

Share this post


Link to post
Share on other sites
psamty10    148

class CBuilding
{
public:
CBuilding(int numBalls = MAX_BALLS_IN_BUILDING);
private:
CBall *Balls;
}

CBuilding::CBuilding(int numBalls)
{
Balls = new CBall[numBalls];
}


Share this post


Link to post
Share on other sites
Beer Hunter    712
If you need a destructor, you probably need a copy-constructor and assignment operator, too. Don''t forget them either.
The easy way is to use a std::vector.

class CBuilding
{
public:
CBuilding(int numBalls = MAX_BALLS_IN_BUILDING);
private:
std::vector<CBall> Balls;
}

CBuilding::CBuilding(int numBalls)
{
Balls.resize(numBalls);
}

Share this post


Link to post
Share on other sites
psamty10    148
quote:
Original post by bobstevens
Do NOT forget your destructor:
CBuilding::~CBuilding()
{
delete [] Balls;
}



Yes... quite right. Thanks for pointing that out... i forgot to include it in my original soln.

Share this post


Link to post
Share on other sites