In a class, the deconstructor has the task of cleaning up all of the memory that was taking by the object during it's lifetime (as well as other housekeeping); if there is any data left hanging around, it needs to be gotten rid of forever or else your program will "leak" memory, or progressively take up more and more without stopping or letting it go.
When you create a virtual function, whenever you base a new class off of the original, you are forced to write a new version of the function. This is a good practice because whenever the class changes, you are usually dealing with different ways of creating data and accessing memory. The destructor needs to change also in order to do a proper cleanup.
2006-12-12 12:28:29
·
answer #1
·
answered by يا حسين 4
·
0⤊
0⤋
If you have a base class A and a derived class B, then in C++ you can create a new B object and assign it to an A pointer. Then you can call the delete operator on the A pointer to free the memory. If you do this and your destructor is not virtual, then only the A destructor will be called, and no B specific cleanup will happen - causing memory leaks and the like. If you declare your destructor virtual, then the B destructor will properly be called (first). Any situation where you would delete an object via its base class pointer will result in this situation and require a virtual destructor for the compiler to generate correct code and call the correct destructor. If you don't do this type of thing, you don't need a virtual destructor, but its usually a good idea to do this in most cases anyway since you might end up doing this type of thing somewhere down the line and forget to change your destructors to virtual.
Code snippet example:
A * p = new B;
delete p; // Needs virtual destructor
B * p = new B;
delete p; // non-virtual destructor is fine
2006-12-12 22:53:49
·
answer #2
·
answered by Mark W 1
·
0⤊
0⤋
See the C++ FAQ for a good answer:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
2006-12-12 22:47:44
·
answer #3
·
answered by The Swede 2
·
0⤊
0⤋
well it's more of one of those "Why not" things
2006-12-12 20:27:14
·
answer #4
·
answered by uofmeuchre 3
·
0⤊
0⤋