Jump to content
  • Advertisement
Sign in to follow this  
NIm

How to initialize an array of objects

This topic is 4830 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am using c++, and I have an class, creature, and itis rather meaningless without it's constructor, and I need an array of them. I've tried
class creature(args);
and
class creature(args);
Is this meant to be done? it did work when there was a null constructor... I need help doing it with a non-null constructor. Thank you for your time

Share this post


Link to post
Share on other sites
Advertisement
Do this, assuming your constructor has two arguements.


cl ob[3] =
{
cl(1, 2),
cl(3, 4),
cl(5, 6)
};


Share this post


Link to post
Share on other sites
you could hold an array of pointers:
creature *arr[3];
for(int i=0;i<3;i++)
arr=new creature(args);

then dont forget:
delete[] args
when youre done.

EDIT:
or use the obove poster's idea if you cannot use pointers.

Share this post


Link to post
Share on other sites
unfortunately C++ does not contain syntax to do what you want it to. So we have to look at alternatives. The two previous posters, dxFoo and supercoder74, presented two, but there are others, all with various tradeoffs. You could just make the array and have it call the default constructer and then change the values in each cell. The downside is that you ruin the purity of allocation=initialization, but then again programming is about using common sense and making tradeoffs. Another is that you use a vector and push_back each instance of Creature as you create it. So just think about which factors are more important and go with the solution. Too bad that C++ doesn't have that feature.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!