Why would you make a destructor virtual?

Answer Posted / chandra

Vitual destructor is used

(1) whenever the base class object pointer points to
derived class object,and is being created using new.
i.e class base - base class
in main - base bptr;
class derived - derived class
in main - bptr = new derived();

Then whenever we use "delete bptr" at runtime always the
memory of bptr is freed but not derived because here the
pointer is of type base and not of derived.

Note: The destructor that gets invoked is the one that
associated with the type of the object.

Simple rule of thumb: Make your destructor virtual if your
class has any virtual functions.

Example:
#include <iostream.h>
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void main()
{
Base *Var = new Derived();
delete Var;
}


Is This Answer Correct ?    9 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is function overloading c++?

562


What is code reusability in c++?

659


When does the c++ compiler create temporary variables?

560


What is c++ & why it is used?

579


Why is it called c++?

575






What is a set in c++?

524


How can you quickly find the number of elements stored in a dynamic array?

566


What are c++ stream classes?

549


What is object oriented programming (oop)?

613


Can member functions be private?

587


What is double in c++?

553


Can union be self referenced?

566


Distinguish between a # include and #define.

637


What is jump statement in C++?

608


When are exception objects created?

601