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
What is function overloading c++?
What is code reusability in c++?
When does the c++ compiler create temporary variables?
What is c++ & why it is used?
Why is it called c++?
What is a set in c++?
How can you quickly find the number of elements stored in a dynamic array?
What are c++ stream classes?
What is object oriented programming (oop)?
Can member functions be private?
What is double in c++?
Can union be self referenced?
Distinguish between a # include and #define.
What is jump statement in C++?
When are exception objects created?