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
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
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()
.
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.
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.
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)