jeudi 5 décembre 2019

is it possible to create an array of type declarations in c++?

I was wondering if there was a way to create an array that contains type declarations to more easily and more flexibly declare a larger number of variables of different types.

For instance, what I'm trying to do is have an array of a parent class and I want to declare a dynamic pointer array of the parent class' children.

Here is an example class declaration:

class parent {
   private:
      int x;
}

class child1 : public parent {
   private:
      int y;
}

class child2 : public parent {
    private:
      int z;
}

Here is what I'm doing manually:

parent *array[100];
int count = 0;
int child1_num = 25, child2_num = 75;
for (int i = 0; i < child1_num; i++) {
   parent[count++] = new child1;
} 
for (int i = 0; i < child2_num; i++) {
   parent[count++] = new child2;
}

I am hoping I can get it in a form similar to:

parent *array[100];
child_type type[2] = {child1, child2};
int child_num[2] = {25, 75};
int count  = 0;
for (int i = 0; i < 2; i++) {
   for (int j = 0; j < child_num[i]; j++) {
       array[count++] = new type[i];
   }
}

If there is a better way of going about this? I couldn't come up with anything else.

Aucun commentaire:

Enregistrer un commentaire