Learn from numnum---try to answer Wendywendy's question

jabber (jabber)
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >
Why do we need a virtual desctructor?

In our C++ programm, if there is an inheritance tree, an object usually has several data types. Take Animal-->{Snake, Fish, Bird} as an example. Now we create 3 Snakes, 4 Fish and 5 Birds on the heap using "new" and put them in an array of Anamals. Now we write a for-loop to destroy these Animals using "delete". Recall that these Animals are created a la Snake, Fish and Bird, respectively. If we did not use the key word "virtual" on the Anamal destructor but overrid it in the definition of Snake, Fish and Bird, the above for-loop will lead to a memory leakage---The cleanup is incomplete because only the Animal's destructor has been invoked! To answer the question briefly, I would like to say: By using virtual destructor, we can quarantee cleanup on the heap and prevent our code from memeory leaking.

Another concept directly related to virtual desctructor is "pure virtual desctructor". It has a special syntax "....=0;". The reason that C++ designer introduced "pure virtaul desctructor" is to prevent people from instantiating the base class. Take Animal an example again. If somedody has bought 100 Animals, I can assure you that they are dogs, or cats, or goats, .In the software, it does not make much sense in creating an abstract Animal. In such a case, a good practice is to make Animal's destructor "pure virtual". Then, the users of the Animal class can only create Animals according to Parrot, Toad, Lizard..

If you need to answer such questions orally in a job interview, it is a good idea to use some examples. By doing so, you can easily argue away those interviewers. In any case, you shouldn't be argued away.
<本文发表于: 相约加拿大:枫下论坛 www.rolia.net/f >

2001-6-20 -04:00

回到话题: Learn from numnum---try to answer Wendywendy's question

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT杂谈