×

Loading...

Topic

  • 工作学习 / IT杂谈 / Learn from numnum---try to answer Wendywendy's question
    本文发表在 rolia.net 枫下论坛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
    • wow, I don't know you are also good at C++. But I guess all the languages are similar to each other. I am still a little surprised when I saw "try...catch" in C++.
      • Thank you for encouragement. I am quite green in C++.
    • It's great! Thanks for the details, jabber
    • Thank u ,Jabber, I am so glad to see you again.
    • what's "pure virtual destructor"?
      • Here is an example...
        class Animal{
        public:
        virtual ~Animal() =0;
        } ;

        Animal::~Animal() {}

        This is a dummy example. However, it can prevent people from creating an Animal directly.