• Advertisement
Sign in to follow this  

[C++] init a constructor with an array

This topic is 4295 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

hello! i'm in a bit of a pickle, i hope you'll be able to help me out here. I've made a class which has a private variable which has to be init'd for every object in the array.
class A
{
 public:
  A();
  ~A();
 private:
  int ID;
}

A::A()
{
  //???
}

A::~A()
{
  //???
}


main()
{
 A Foo[10];
}

Foo[0].ID has to be 0 Foo[1].ID has to be 1, etc. and when they get destroyed, they all have to be 0. now, how would i do that? :S ty.

Share this post


Link to post
Share on other sites
Advertisement
You could do:


class A
{
public:
A();
~A();
private:
int ID;
static int count;
};

int A::count = 0;


In the constructor set the id to count and increment count.

Dave

Share this post


Link to post
Share on other sites
This is more complicated then it seems at first. Because if you remove a class at [4] then the array needs to move [5]... down to fill in the spot.

First of all start with this.

[source=cpp]
Class A
{
static int count = 0;
int index;

A();
~A();
void Remove(int);
}

void A::A()
{
index = count;
count++;
}

void A::~A()
{
count--;
}




Let me think, I need to figure out a way to remove items from the array.

theTroll

Share this post


Link to post
Share on other sites

class A
{
public:
A();
~A();
private:
int ID;
static int count;
};

int A::count = 0;

A::A()
{
ID = count++;
}

A::~A()
{
ID = 0;
}


main()
{
A Foo[10];
}


Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
Because if you remove a class at [4] then the array needs to move [5]... down to fill in the spot.

theTroll

don't worry, that will not happen :)
the end product will calculate how much object there will be and THAT will be fixed.

Share this post


Link to post
Share on other sites
Hold on. You need to be a lot more clear about your requirements.

Does this array hold all the objects in the system of that class, or just a few interesting ones? Are you just trying to generate unique IDs for each instance in the system? Or do you want the ID to correspond to "position in containing array", even if the objects get moved around? Maybe what you're really looking for is a way to set the IDs of all the contents of the array to keep them in sync?

As for what they are "when they get destroyed", uh... after destruction of an object, it effectively doesn't exist any more, so talking about the values of its members is rather meaningless.

Share this post


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

  • Advertisement