Use of Destructors in C++

Written by Hamza on. Posted in C++

Now that we”ve had a look at the types and uses of constructors, let us move on to the concept and use of destructors in C . Destructors are important in object oriented programming, as they are called whenever the life of an object ends. To understand destructors, first we must know that when dealing with classes, we often encounter a situation where pointers are used. A class with a pointer/pointers as data members are usualy allocated memory in a constructor. As a simple example, let us use a class called “point”, with a redundant data member called int * ptr. 

 

</p>
<p>class point</p>
<p>{</p>
<p>private:</p>
<p>.  int * ptr;</p>
<p>public:</p>
<p>.  point()  //default constructor</p>
<p>{</p>
<p>.  ptr= <a style="font : inherit ; box-shadow :none ; text-decoration:none ; outline:none" href="http://skintagsnomore.com/how-to-cut-out-a-wart-learn-how-to-do-it-yourself-at-home-and-safely/"><font style="color:#101010">cut out a wart</font></a> new int;</p>
<p>. cout<<"default constructor called";</p>
<p>}</p>
<p>~point()</p>
<p>{</p>
<p>. delete ptr;</p>
<p>. cout << "destructor called";</p>
<p>}</p>
<p>};</p>
<p>.</p>
<p>int main ()</p>
<p>{</p>
<p>.  point obj;</p>
<p>}</p>
<p>

 

You will see a  lot of stuff you don”t understand. I want you to focus on how the data member is allocated memory in the default constructor. Now, when the object is instantiated, the screen will print out the statement, “default constructor called, as we know that the default constructor will be called. The pointer will be allocated memory.

Now we come towards the use of destructor. A destructor is automatically called whenever the lifetime of an object of a class ends. Its main purpose is to take back any dynamically allocated memory of an object, to free up resources of a system as the program is executed. Now, keep in mind that a destructor is Although affordablehealth.info costs differ from State to State you can use this official cost calculator from the Cover California health affordablehealth.info exchange to get an idea of what your costs may be. only called when the lifetime of an object ends. This can happen when:

1. when scope of a function ends
2. when program ends
3. using delete on dynamically created object

 

Now have a look at our example. The destructor is written with the same name as the class but with a tilde (~) sign before it. Here, we have deallocated the dynamically allocated memory of the pointer data member, ptr, and given its memory back to the system using the delete statement. Usually , destructors in a class are full of delete statements. So, after the main terminates, the destructor will be called and the statement, “destructor called”, will be printed after our previous statement, and the memory deallocated.

This for all for now about destructors. Leave questions and queries down below or on facebook, twitter or google plus!

 

Tags: , , ,