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

What are multiple inheritances (virtual inheritance)? What are its advantages and disadvantages?

1099


What's c++ used for?

1156


What is function declaration in c++ with example?

1178


What is virtual destructor? What is its use?

1119


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?

1147


What is the difference between *p++ and (*p)++ ?

1408


Can user-defined object be declared as static data member of another class?

1071


Write a program using merge () function to combine the elements of array x[ ] and y[ ] into array z[ ].

1112


What does catch(…) mean?

1169


What is encapsulation in c++ with example?

1041


In what situations do you have to use initialization list rather than assignment in constructors?

1104


What is the difference between mutex and binary semaphore?

1291


What is a c++ class?

1149


If there are two catch statements, one for base and one for derived, which should come first?

1078


Explain how to initialize a const member data.

1080