Search code examples
c++arrayspointersheap-memorydelete-operator

How to delete a pointer array full of class objects


I am working through some university tutorials and I have to delete this array I have made with pointers and I should see the deconstructors for each object in the array called as I delete it. Here is the code. (Csprite is the base class, CpowerPill, Cghost and Cpacman are derived classes)

    Csprite * psprites[3]; 

psprites[0]=new CpowerPill;
psprites[1]=new Cghost;
psprites[2]=new Cpacman;

delete psprites[0,1,2];


    cin >> endPro;

All I get when I run this a single deconstructor call from the base class when I should get 3 different deconstructors all from the respective derived classes. Any help would be really appreciated.


Solution

  • [I'm assuming that your code compiles; i.e. Csprite is the base class]

    Since you've used new separately on each element, you need to use delete separately on each element:

    delete psprites[0];
    delete psprites[1];
    delete psprites[2];
    

    The comma notation that you've used in delete psprites[0, 1, 2]; doesn't do what you think it does. 0, 1, 2 is just an expression with value 2, so all you're doing is deleting the final element.

    As the array psprites is stack-allocated, you don't need to delete that. In fact, to do so would be undefined behaviour.

    One more thing, you need to ensure that Csprite has a virtual destructor, or you'll leak memory. You can do that by writing virtual ~Csprite(){} in its class declaration.