Thursday, September 18, 2008

C++ Virtual destructors - in c++ programming need for a Virtual Destructor

What is the need for a Virtual Destructor ? 

Destructors are declared as virtual because if do not declare it as virtual the base class destructor will be called before the derived class destructor and that will lead to memory leak because derived class’s objects will not get freed.Destructors are declared virtual so as to bind objects to the methods at runtime so that appropriate destructor is called.

Answer2:-

The virtual destructor has the same purpose as a virtual function. At runtime looking at the type of object referred by a pointer or reference it is decided which destructor to call -- the destructor of the base class or the destructor of the derived class.

For example, suppose B is a base class and D is a class derived from B and suppose both classes have declared their destrcutor as virtual. Suppose a pointer B *ptr is initialized as follows:

B *ptr = new D();

Now the ptr is of type B* but points to an object of D. So when this object is freed or goes out of scope D's destructor will be called since the destructors have been declared as virtual.

No comments:

Post a Comment

Thanks to given comments.......

My Blog List