Is it possible to get memory leak when deallocate a derived class object by deleting its base class pointer(if the base class has virtual destructor)? What about the base class doesn't have virtual destructor?
Printable View
Is it possible to get memory leak when deallocate a derived class object by deleting its base class pointer(if the base class has virtual destructor)? What about the base class doesn't have virtual destructor?
If the base class has a virtual destructor, all the derived class destructors will be called. If not, they won't. Hence, every base class should have a virtual destructor.
Now, it's still possible to have a memory leak if your class does not free dynamic memory correctly. But this is not the result of a destructor not being called.
Jeff
Just to step on Jeff's toes a little bit (sorry, jeff :rolleyes: ), note that, by base class he means a class that is specifically designed to be derived from, not that all classes should be given a virtual dtor as a matter of course. It's cause of constant annoyance to me that VC++ insists on adding a virtual destructor if you use the "Add class..." menu option. The first thing that I always find myself doing is deleting the (default) ctor and the dtor that it "helpfully" adds for you.Quote:
Originally posted by jfaust
Hence, every base class should have a virtual destructor.
Just thought I'd point that out for any of out younger viewers who might be watching.
Ouch, my toes!
But right, "designed to be derived from" is more appropriate than "base class". It should be a design decision rather than an implementation decision.
Jeff