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

Describe friend function & its advantages.

719


Can you pass an array to a function in c++?

545


Given the following seqment of code containing a group of nested if instructions: y = 9; if ((x==3) || (x == 5)) y++; else if (x == 2) y *= 2; else if (x == ) y-= 7; else y = 8; if the value of x is 4 before the nested IFs are executed, what is the value of y after the nested IFs are executed?

1589


What are the extraction and insertion operators in c++? Explain with examples.

656


Explain unexpected() function?

589






What is a singleton c++?

552


Evaluate the following expression as C++ would do :8 * 9 + 2 * 5 a) 82 b) 79 c) 370 d) list

618


What is the extension of c++?

518


the maximum length of a character constant can be a) 2 b) 1 c) 8

602


Explain class invariant.

589


What is virtual function? Explain with an example

593


What is the difference between while and do while loop? Explain with examples.

604


What is ios in c++?

650


What are separators in c++?

628


Is map thread safe c++?

636