C++ Destructor - Learn C++ , C++ Tutorial , C++ programming



 c++-destructor

Learn c++ - c++ tutorial - c++ destructor - c++ examples - c++ programs

What is destructor in C++?

  • Destructor is a member function which destructs or deletes an object.

When is destructor called?

A destructor function is called automatically when the object goes out of scope:

  • the function ends
  • the program ends
  • a block containing local variables ends
  • a delete operator is called
 destructor code class in c++

The Class Destructor

  • A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
  • 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.
  • Following example explains the concept of destructor:
#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;
}

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

Can there be more than one destructor in a class?

No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type.

When do we need to write a user-defined destructor?

If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.


Related Searches to C++ Class Destructor