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 is an adjust field format flag?

1070


What does new return if there is insufficient memory to make your new object?

975


How will you call C functions from C ++ and vice-versa?

1078


Explain pass by value and pass by reference.

1002


What do the keywords volatile and mean mutable?

1004


What is a sequence in c++?

959


What is a storage class? Mention the storage classes in c++.

975


How can virtual functions in c++ be implemented?

1058


C is to C++ as 1 is to a) What the heck b) 2 c) 10

1005


How much do c++ programmers make?

1055


Write a corrected statement in c++ so that the statement will work properly. if (4 < x < 11) y=2*x;

1964


When we use Abstract Class and when we use Interface?where we will implement in real time?

2134


What do you mean by public protected and private in c++?

999


Is there any function that can skip certain number of characters present in the input stream?

1012


Define copy constructor.

1056