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

jabber (jabber)
本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
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.
更多精彩文章及讨论,请光临枫下论坛. 网址: rolia.net/zh
2001-6-20 -04:00
This post has been archived. It cannot be replied.
Page address has been copied. To share, click to copy page address.
Share Online by QR Code

Back To Topic: Learn from numnum---try to answer Wendywendy's question

Back To Forum: HOME枫下论坛枫下论坛主坛工作学习IT杂谈