Delete Question

Started by
6 comments, last by Tonin 18 years, 1 month ago
Hi, I have a quick question about using delete with polymorphic classes in c++. If you call delete on a base class pointer that is actually pointing to an object of a derived class, does all of the memory get deallocated, or just sizeof(BaseClasss) ? Thanks, ~Andy
Advertisement
Quote:Original post by Tonin
Hi, I have a quick question about using delete with polymorphic classes in c++.

If you call delete on a base class pointer that is actually pointing to an object of a derived class, does all of the memory get deallocated, or just sizeof(BaseClasss) ?

Thanks,
~Andy



All the memory will be deleted. All the memory that new gave you. If your destructor isn't virtual, none of the other destructors will be called. That leaves room for memory leaks.
So long as the base class has a virtual destructor, everything will work properly.

class WorkingBase{public:   virtual ~WorkingBase() {}};class WorkingDerived : public WorkingBase{};class NotWorkingBase{public:    ~NotWorkingBase() {}};class NotWorkingDerived : public NotWorkingBase{};int main(){   WorkingDerived* good = new WorkingDerived();   NotWorkingDerived *bad = new NotWorkingDerived();   delete (WorkingBase*)good; //calls ~WorkingDerived() and ~WorkingBase()   delete (NotWorkingBase*)bad; //only calls ~NotWorkingBase()}

CM
Ok thanks, The need for virtual destructors isn't for the object itself then, just for anything it needs to cleanup. I kind of thought that would be the case but couldn't find anything that actually said so ;)
Quote:
The need for virtual destructors isn't for the object itself then, just for anything it needs to cleanup.


I'm a little confused as to what you mean by that, but it sounds like you mean "the base class doesn't need a virtual dtor, only the subclasses do," which is incorrect. The base dtor needs to be virtual as well if you are going to delete an object through a base class pointer.
Sorry, that was a bit unclear. What I meant was that you don't need a virtual destructor to have delete work properly on a derived class (basically what rip-off said). Obviously you would need one if you wanted to call the derived destructor, but it isn't needed if all you want to do is delete the object itself.

Hope that's a bit clearer (and that I understood what rip-off said right),
~Andy
If your class doesn't have a virtual destructor, calling delete on a pointer of a different type than the actual type of the class results in undefined behavior. That is if you have:

Base * b = new Derived;
delete b;

If Base does not have a virtual destructor then all bets are off as to what is freed. There's a good chance that it'll corrupt the heap in addition to not calling the Derived destructor.
Ok, thanks for the correction. I'm surprised that none of the tutorials or books I've read mention this.

~Andy

This topic is closed to new replies.

Advertisement