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?
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
.
No, you have to explicitly delete each item in the array:
for (int i = 0; i < 3; ++i)
{
delete arrayPtr[i];
}
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