Destructor
The purpose of a destroyer is to destroy objects created by a constructor. Like a constructor, the destructor is a member function with the same name as the class name but preceded by a tilde (~). This is a special member function of a class that is performed each time an object in its class leaves its field or when delete is applied to a pointer to the object in that class.
Example Program:
#include <iostream> using namespace std; class Line { private: double length; public: void setLength( double len ); double getLength( void ); Line(); // constructor declaration ~Line(); // destructor declaration }; 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; line.setLength(6.0); // set line length cout<<"Length of line : " ; cout<< line.getLength() <<endl; return 0; }
Output:
