Let's say I want to implement a bag of worms. I have class Worm, which has an int attribute ID. I also have a class Bag:
class Bag{
// pointer to a 1D array of pointers to all the worms
Worm** population;
// constructor
Bag(){
// initiate 1D population of the worms
int N = 100;
Worm** population = new Worm*[N];
for (int i=0; i<N; i++){
Worm new_worm(i);
population[i] = &new_worm;
}
}
}
since N is known at the time of compilation I am not sure if the array has to be dynamically allocated?
My problem is that later in the code I would like to execute:
Bag bag();
int ID = bag.population[10]->ID;
and the code gets compiled but when I execute I get Segmentation fault: 11. I have checked (by commenting) that the problem is caused by the exact line of ID extraction.
How should I access the fields and call methods of class Worm in the bag?