Friday, 23 September 2016

DESTRUCTORS


If a constructor is created in a program for initializing or giving values to the variables then it should also have a destructor to destroy the object. A destructor is used to destroy the objects that have been created by the constructor.
It is also a memeber function of the class with same name as class but is preceded by title('~'). 

Syntax: ~destructor-name()
                 { body }

NOTE: No matter how many constructors are there in a program, there will be only one destructor needed to destroy all the objects.


Why do we need Destructors?

During the construction of an object, resources may be allocated, that means memory is allocated to an object. Now before destroying an object we need to deallocate them. So destructor is used for clean-up tasks.




Example:

class Sample
{
int a;
int b;
~Sample(){cout<<"Destructing";} //Destructor

public: 
            Sample(){a=0; b=0;}
            void fun1();
            void fun2();
};

Now if the objects of class "Sample" are created in order then their objects are destroyed in reverse order. This is done by Destructor.


For Example: 

{
Sample s1;      //Object s1 created 
Sample s2;      //Object s2 created

//Object s2 destructed 
//Object s1 destructed 
}

The objects s1 and s2 were destroyed by the destructor "~Sample()".


For More Help:


1 comment:

  1. Thanks.. I hope you like it. I will post more topics regarding C++.

    ReplyDelete