A Beginners tutorial in Virtual Destructor
Virtual Destructor
Virtual Destructor is used to release the derived class objects in a proper order....
Consider an Example:
Code: Cpp
#include<iostream.h>
class Base { public: Base() { cout<<"Base class constructor"<<endl; } virtual void show() { cout<<"Base class Inside show function"<<endl; } void display() { cout<<"Display method"<<endl; } [B]~Base ()[/B] { cout<<"Base class Destructor"<<endl; } };
class Derived : public Base { public: Derived() { cout<<"Derived class constructor"<<endl; } void show() { cout<<"Inside derived show function"<<endl; } void display() { cout<<"Inside derived display function"<<endl; } ~Derived() { cout<<"Derived class destructor"<<endl; } };
void main() { Base *b=new Derived; b->show(); b->display(); delete b; }
Output for the above program is:-
Code:
Base class constructor
Derived class constructor
Inside derived show function
Display function
Base class Destructor
Consider a line
Base *b=new Derived;
Pointer object created for base class (Base class constructor and Derived class constructor automatically called during object creation phase)...
Consider a line
delete b;
In the above line base class object b destructs automatically (without destructing derived class
To avoid it if we have a concept called virtual destructor .
Example:
Code: Cpp
#include<iostream.h> class Base { public: Base() { cout<<"Base class constructor"<<endl; } virtual void show() { cout<<"Base class Inside show function"<<endl; } void display() { cout<<"Display method"<<endl;
} [B]virtual ~Base ( )//virtual destructor See the virtual keyword[/B] { cout<<"Base class Destructor"<<endl; } };
class Derived : public Base { public: Derived() { cout<<"Derived class constructor"<<endl; } void show() { cout<<"Inside derived show function"<<endl; } void display() { cout<<"Inside derived display function"<<endl; } ~Derived() { cout<<"Derived class destructor"<<endl; } };
void main() { Base *b=new Derived; b->show(); b->display();//if a method is not at all virtual only base class function called delete b; }
Output is :-
Code:
Base class constructor
Derived class constructor
Inside derived show function
Display function
Derived class destructor
Base class Destructor
In the above program , Object destructs in a proper order(b'coz base class destructor is made as virtual......)
V-Table:
Normally v_table(virtual table ) is created for each and every class .The v-table normally contains the addresses of the virtual functions and the pointer to point the function(called as v-pointer). Whenever Virtual function is called , v-table decides to the function address..........
|