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 are multiple inheritances (virtual inheritance)? What are its advantages and disadvantages?
What's c++ used for?
What is function declaration in c++ with example?
What is virtual destructor? What is its use?
If a base class is an adt, and it has three pure virtual functions, how many of these functions must be overridden in its derived classes?
What is the difference between *p++ and (*p)++ ?
Can user-defined object be declared as static data member of another class?
Write a program using merge () function to combine the elements of array x[ ] and y[ ] into array z[ ].
What does catch(…) mean?
What is encapsulation in c++ with example?
In what situations do you have to use initialization list rather than assignment in constructors?
What is the difference between mutex and binary semaphore?
What is a c++ class?
If there are two catch statements, one for base and one for derived, which should come first?
Explain how to initialize a const member data.