pickzy.com

C  |  C++  |  Objective-C  |  VC++  |  Win32  |  MFC  |  Java  |  Php  |  Delphi  |  Visual Basic  |  .Net  |  Networking  |  General  |  Games  |  Jobs  |  Javascript  |  




Menu

pickSourcecode.com


        

 




 

Cpp > Articles

 

Cpp - Virtual Destructors

Destructors :
Destructor is a member function,which gets called when the object goes out of scope.
That is all cleanups and final step of class destruction is done in destructors
Destruction is done in the following order,
1.Derived class destructor
2.Base calss destructor

Virtual Destructors :
When a destructor is defined in both base and derived classes, during a function call,
the destructor in derived class gets executed and not the one defined in Base class.
In order to execute both base and derived destructors, the destructor in base class must be declared as virtual.


class base
{
public:
    base()
    {
        cout<<"Constructor : Base" <<endl;
    }
    virtual ~base()  //Base class destructor is defined as virtual
    {
        cout<<"Destructor  : Base" <<endl;
    }
};

class derived :public base
{
public:
    derived()
    {
        cout<<"Constructor : Derived" <<endl;
    }
   ~derived()
    {
        cout<<"Destructor  : Derived" <<endl;
    }
};

int main()
{
    base *val=new derived();
    delete val;
}

Output :
 Constructor : Base
 Constructor : Derived
 Destructor  : Derived
 Destructor  : Base
 
Note :
  If the base class destructor is not declared as virtual, only the derived class destructor will be called.
 

 
Privacy Policy | About Us