In C++, Destructor is a special class function that destroys an object once the scope of the object ends. The destructor is typically invoked or called automatically by the compiler when the object goes out of scope.
The destructor has the same syntax as that of the constructor. The destructor uses the same class name with a tilde ‘~‘ sign as a prefix to it.
Syntax:
class A
{
public:
~A();
};
Note- Destructors will never have any arguments.
Example:
#include <iostream>
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
void main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
getch();
}