Sign in to follow this  
homeboye

[C++] init a constructor with an array

Recommended Posts

homeboye    115
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
dave    2187
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
TheTroll    883
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
ronkfist    100

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
homeboye    115
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
Zahlman    1682
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this