Chapter: Object Oriented Programming and Data Structure : Data Abstraction & Overloading

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.

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:

 

voidsetLength( double len );

doublegetLength( 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


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Object Oriented Programming and Data Structure : Data Abstraction & Overloading : The Class Destructor |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.