Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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

How do you write a function that can reverse a linked-list?

1114


Explain how a pointer to function can be declared in C++?

1065


When do we run a shell in the unix system? How will you tell which shell you are running?

984


What is a constant reference?

1077


Explain the virtual inheritance in c++.

1069


What are pointer-to-members? Explain.

1152


What is helper in c++?

1093


What does namespace mean in c++?

1078


What is private public protected in c++?

1053


What are the effects after calling the delete this operator ?

1058


Why c++ is created?

1006


What are virtual constructors/destructors?

1022


What is the output of the following program? Why?

1146


What is fflush c++?

1025


If you hear the cpu fan is running and the monitor power is still on, but you did not see anything show up in the monitor screen. What would you do to find out what is going wrong?

1133