|
-
August 6th, 2002, 04:10 PM
#1
Question about deleting base class pointer
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?
-
August 6th, 2002, 05:50 PM
#2
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
-
August 7th, 2002, 04:32 AM
#3
Originally posted by jfaust
Hence, every base class should have a virtual destructor.
Just to step on Jeff's toes a little bit (sorry, jeff ), 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.
Just thought I'd point that out for any of out younger viewers who might be watching.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
August 7th, 2002, 09:45 AM
#4
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|