3

Possible Duplicate:
When to use virtual destructors?
Virtual destructor and undefined behavior

i am new to c++ and programming,i have observed that destructor is always declared virtual. may i know why is it so?

Thanks in Advance

Community
  • 1
  • 1
ken
  • 816
  • 1
  • 9
  • 25
  • 1
    Welcome to Stack Overflow. Please use the search before posting new questions; many have already been asked and answered. – Brian Roach Feb 18 '12 at 06:00

4 Answers4

12

It is not always declared virtual. It is declared virtual when you want to delete an object through a pointer which of type base class, then it is required to make the destructor of base class virtual, to avoid undefined behavior.

class A{ public: ~A(); }; //note:  ~A() is not virtual
class B : public A {};

A *pA = new B();

delete pA; //invokes undefined behavior, as ~A() is not declared virtual

In such cases, you need to make the base class destructor virtual:

class A{ public: virtual ~A(); }; //note:  ~A() is virtual
class B : public A {};

A *pA = new B();

delete pA; //Well defined behavior, as ~A() is declared virtual

In this case, delete pA will first invoke ~B() (because pA is pointing to an object of type B), then it will invoke ~A().

Nawaz
  • 353,942
  • 115
  • 666
  • 851
3

It's declared virtual so that inheriting classes will remember to override this method to do their own cleanup. This is important to prevent memory leaks.

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
Oleksi
  • 12,947
  • 4
  • 56
  • 80
  • 1
    Wrong. destructors cannot be overloaded. – Nawaz Feb 18 '12 at 06:05
  • This is a mean to allow upper in the chain of inheritance pointer to call its own destructor method, ie. BaseClass* ptr = new DerivedClass(); delete ptr; So it will let "ptr" to correctly call the correct destructor method of its own. – haxpor Feb 17 '13 at 06:05
0

Destructors are not always declared virtual.

A virtual destructor is important if a class is intended to be used as a public base class. Without a virtual destructor, the following would not work:

class A {public: ~A() {} };

class B : public A {public: ~B() {}};

A *a = new B;
delete a;

The last line will not do the right thing, because it will not call B's destructor. To correct this, A's destructor must be virtual.

Note that this is only necessary for classes that you intend to be derived from, and those that you intend the user to use public inheritance. This generally is not the case for most classes.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

In terms of inheritance it makes sense to make a destructor as virtual for the base class so as the proper class object is freed when a destructor for that particular class is called through a base class pointer. So, it follows the reverse order of inheritance. (child to parent)

DarkKnight
  • 37
  • 4