Reputation: 492
I am not sure how pertinent my question is, but here it goes.
I know that we should only call the destructor explicitly when we allocated memory on the heap.
So let's say we have two classes: Animal and Dog which is a subclass on Animal.
Animal a* = new Dog();
//-------Do something here-----//
a -> ~Animal();
Again, let us say that Animal contains several fields that are dynamically allocated and that the Dog class adds a couple more dynamically allocated fields.
Because Dog has more fields, calling the Animal destructor will result in memory leakage. Is this simply bad programming style or we can get a workaround?
I suppose we need to cast the pointer to the Dog type and then call the destructor, but I am unable to find any reference on how to do this correctly.
Upvotes: 0
Views: 52
Reputation: 67789
Because Dog has more fields, calling the Animal destructor will result in memory leakage.
That doesn't happen if Animal
's destructor is virtual
.
Furthermore, you do not need to call ~Animal()
. The one exception is if you are writing your own allocator. Normally you call delete a
instead.
Upvotes: 7
Reputation: 63124
I know that we should only call the destructor explicitly when we allocated memory on the heap.
Nope, nope, nope, nope, nope. You never, ever call a destructor explicitly except in very specific cases (placement new and unions are the two that I know of).
What you need to do here is call delete
on your pointer. And as rlbond already stated, deleting through a base pointer is fine as long as the destructor of the base class is virtual.
Upvotes: 3