I have 2 questions regarding to the program below: 1. Does the program create only the elements(type rectangle and hexagon) as dynamic, or also the pointers to them are dynamic?
2.why the program doesn't have a delete at the end. for example something like this:(if I assume correctly that only the elements are dynamic..)
for(i=0;i<3;i++)
delete shapeArray[i];
Thank you very much,this website helps me a lot with things that my teachers can't help! Shiran
the program is:
int main()
{
// Create array of pointers to Shapes of various types.
const int NUM_SHAPES = 3;
Shape * shapeArray[] = { new Hexagon(),
new Rectangle(),
new Hexagon()
};
// Set positions of all the shapes.
int posX = 5, posY = 15;
for (int k = 0; k < NUM_SHAPES; k++)
{
shapeArray[k]->setPosition(posX, posY);
posX += 10;
posY += 10;
};
// Draw all the shapes at their positions.
for (int j = 0; j < NUM_SHAPES; j++)
{
shapeArray[j]->draw();
}
return 0;
}
Your program creates an array of pointers to Shape on the stack. The array size is known at compile time from the length of the initializer list {}. Each element in the initializer list is the address of a Shape created on the heap through operator new.
The fact that they are not freed is bad style, your OS will release the dynamic memory allocated when a program exits so it won't have some consequences in this particular case, but leaving memory not deleted make the detection of "true" memory leaks more difficult.
1) Yes. It allocates memory only for the pointers. It creates an array of 3 pointers with the following:
Shape * shapeArray[] = { new Hexagon(),
new Rectangle(),
new Hexagon()
};
2) On program exit, the memory allocated for the pointers will be usually recalimed by the operating system. However, you should delete
them explicitly so as to not rely on what OS does and you may loose track and run into memory leaks as the program grows in size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With