4/23/2017

Virtual desctructor

We  have two classes

class A{

public :

A(){  cout<<”Base constructor of class A “;

~A(){  cout<<”Base destructor of class A “;

};

Class B : public A{

public :

B(){ cout<<”Derived constructor of class B” ;}

~B(){  cout<<”Derived desstructor of class B“};

};

 

Now in main , we have different way to create object;

int main(){

// Case 1 –> Object Creation

//Proper constructor and destructor will be called , nothing need to be done

A objA;

B objB ;

//Case 2—> Pointer with same class dynamic object

A *pA = new A;

B *pB = new B;

….

…..

delete pA ;delete pB; // no issue ,work properly and destructor of A & B class will be called

//Case 3 –> Base class pointer , derived class memory

//in such case , proper destructor will not be called

A *pBase = new B; ///constructor of B & A is called

---------

……..

delete pBase;   //Destructor of A is called

return 0;

}

Case 3 Output

Base constructor of class A

Derived  constructor of class B

Derived  Destructor of class B

---------------------------------------------------------------

Here Base class destructor is not called.

The only problem case is Base Class pointer with derived class memory.

while we assign the memory by statement A *pBase = new B;  compiler know that it will be B class , so proper constructor is called.

when we called delete pBase , it does not know which class memory it hold in run time. That s why we should have a mechanism so that system can call destructor of class B at run time.

to achieve the same , we need to create the destructor as virtual .Once we declare destructor as virtual system automatically delete proper memory & call the destructor of class B.

to resolve the issue of dynamic memory allocation of derived class in Base class pointer & avoid Memory leak , we need to have virtual destructor.

so we need to define the class like this

class A{

public :

A(){  cout<<”Base constructor of class A “;

virtual ~A(){  cout<<”Base destructor of class A “;

};

Class B : public A{

public :

B(){ cout<<”Derived constructor of class B” ;}

~B(){  cout<<”Derived desstructor of class B“};

};

int main(){

//Case 3 –> Base class pointer , derived class memory

 

A *pBase = new B; 

---------

……..

delete pBase;   //Destructor of A is called

return 0;

}

Case 3 Output

Base constructor of class A

Derived  constructor of class B

Derived  Destructor of class B

Base destructor of class A

No comments:

Post a Comment