Answered Questions

  • what is the use of virtual destructor?

    mehulgala177

    • Sep 22nd, 2011

    You should always keep your destructors virtual when u r dealing with Inheritance. Try this Code :

    Code
    1. #include <iostream>
    2. #include <tchar.h>
    3.  
    4. using namespace std;
    5.  
    6. class Parent
    7. {
    8. public:
    9.         virtual ~Parent()
    10.         {
    11.                 cout << " Destroying Parent
    12. ";
    13.         }
    14. };
    15.  
    16. class Child : public Parent
    17. {
    18. public:
    19.         ~Child()
    20.         {
    21.                 cout << " Destroying Child
    22. ";
    23.         }
    24. };
    25.  
    26.  
    27. int _tmain(int argc, _TCHAR* argv[])
    28. {
    29.         Parent * abc = new Child();
    30.         delete (abc);
    31.  
    32.         return 0;
    33. }
    34.  
    Also try the same code without using virtual keyword before ~Parent() u will see the difference... :)

    rimsha

    • Jul 27th, 2011

    Virtual destructor is used to delete the dynamically allocated memory via a base class ptr.