Destructors  are used to distroy the objects that have been created. when an object goes out of scope, destructor automatically removes from the memory the workspace occupied by the object. Like constructor, destructor is also a member function, which has the same name as its class_name, but preceded by a tilde sign (~). futuer it has no return type.for example the destrucvtor for the class code is defined as follows.
 
    syntax:        ~code( )
                               {  body destructor }

The following are the characteristics of destructors

  • Destructors is used to destroy the work space of the object created
  • Destructors neither takes any arguments nor it returns any value
  • Destructors cannot be overloaded
  • It should have public access in the class declaration
  • It will be invoked implicitly by the compiler whenever an instances of the class to which it belongs goes out of existence
  • The primary  usage of a destructor is to clean up and release memory space for future use
  • Whenever 'new' operator is used in the constructors to allocate memory, we should use 'delete' to free that memory space.


Program:

#include <iostream>

using namespace std;

class Line
{
   public:
      void setLength( double len );
      double getLength( void );
      Line();   // This is the constructor declaration
      ~Line();  // This is the destructor: declaration

   private:
      double length;
};

// Member functions definitions including constructor
Line::Line(void)
{
    cout << "Object is being created" << endl;
}
Line::~Line(void)
{
    cout << "Object is being deleted" << endl;
}

void Line::setLength( double len )
{
    length = len;
}

double Line::getLength( void )
{
    return length;
}
// Main function for the program
int main( )
{
   Line line;

   // set line length
   line.setLength(6.0); 
   cout << "Length of line : " << line.getLength() <<endl;

   return 0;

}

Result:

Object is being created
Length of line : 6

Object is being deleted

Other recommended posts of Constructor and Destructor

Posted by Unknown On 02:28 No comments

0 comments:

Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

Blog Archive

Contact Us


Name

E-mail *

Message *