-->

Virtual destructor

1 minute read

 What is the need of virtual destructor?

v Destructors can be defined as virtual.
v Example: Consider the statements,
base *bptr;
bptr = new derived;
……
……
delete bptr;
v We declare the pointer of the base class, named, bptr and it points to derived class.
v If we expect to use the delete operator on object of base class which is pointed to derived class, we must have to declare the destructor of the base class as virtual.
v The reason is that when we use the delete operator to the object of base class pointed to delivered class the entire block of memory is deleted.
v For example:  if the total size of the non-static data members of base class is ‘n’ and the total size of the data member of derived class is ‘m’ then the total size, ‘n+m’ is deleted.
v If we make the base class destructor as virtual and perform the above delete operation then it deletes only the memory occupied by the derived class members, size ‘m’.