Difference between revisions of "Destructors in C"

From Logic Wiki
Jump to: navigation, search
m (1 revision imported)
 
Line 5: Line 5:
  
 
Following example explains the concept of destructor:
 
Following example explains the concept of destructor:
 
+
<pre class="brush:csharp;">
 
  using System;
 
  using System;
 
  namespace LineApplication
 
  namespace LineApplication
Line 39: Line 39:
 
   }
 
   }
 
  }
 
  }
 
+
</pre>
 
When the above code is compiled and executed, it produces the following result:
 
When the above code is compiled and executed, it produces the following result:
  

Latest revision as of 18:06, 15 June 2016

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters.

Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Destructors cannot be inherited or overloaded.

Following example explains the concept of destructor:

 using System;
 namespace LineApplication
 {
   class Line
   {
      private double length;   // Length of a line
      public Line()  // constructor
      {
         Console.WriteLine("Object is being created");
      }
      ~Line() //destructor
      {
         Console.WriteLine("Object is being deleted");
      }
 
      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }
 
      static void Main(string[] args)
      {
         Line line = new Line();
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
 }

When the above code is compiled and executed, it produces the following result:

Object is being created
Length of line : 6
Object is being deleted