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;
}
Code:
Base class constructor Derived class constructor Inside derived show function Display function Base class Destructor
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;
}
Code:
Base class constructor Derived class constructor Inside derived show function Display function Derived class destructor Base class Destructor
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..........
