Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete operator and arrays?

I have an abstract Base class and Derived class.

int main ()
{
  Base *arrayPtr[3];

  for (int i = 0; i < 3; i++)
  {
    arrayPtr[i] = new Derived();
  }

  //some functions here

  delete[] arrayPtr;

  return 0;
}

I'm not sure how to use the delete operator. If I delete array of base class pointers as shown above, will this call derived class objects destructors and clean the memory?

like image 473
Mike55 Avatar asked Jan 06 '10 11:01

Mike55


2 Answers

You have to iterate over the elements of your array, delete each of them. Then call delete [] on the array if it has been allocated dynamically using new[].

In your sample code, the array is allocated on the stack so you must not call delete [] on it.

Also make sure your Base class has a virtual destructor.

Reference: When should my destructor be virtual.

like image 103
Gregory Pakosz Avatar answered Sep 22 '22 23:09

Gregory Pakosz


No, you have to explicitly delete each item in the array:

for (int i = 0; i < 3; ++i)
{
    delete arrayPtr[i];
}
like image 33
fretje Avatar answered Sep 21 '22 23:09

fretje