[C++] init a constructor with an array

Started by
5 comments, last by homeboye 17 years, 11 months ago
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.
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
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

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];}
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.
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.
ID would just be some random number.
anyways.. it's working fine now,
tnx!

This topic is closed to new replies.

Advertisement