Destructor

A class destructor is called automatically when a class goes out of scope, and is used to clean up and free resources acquired by the object along its lifetime.

 

As with the Constructor, the Destructor uses the same name as the class but is prefixed with a ~ tilde.

 

Destructors take no parameters and have no return value.

 

This example show the destructor between lines 17 to 19, with an added "Object destroyed" message for info:

#include <iostream>
using namespace std;

class Coord {
	private:
		double ordX ;
		double ordY ;
	public:
		Coord() { //this is the constructor. Note the same name as the class
			ordX = 0 ; //initial value
			ordY = 0 ;
		}
		Coord(double overX, double overY){ //overloading the constructor, with different types
			ordX = overX ;
			ordY = overY ;
		}
		~Coord() { //showing that the destructor gets automatically called
			cout << "Object destroyed" << endl;
		}
		void Results() {
			cout << "ordX: " << ordX << ", ordY: " << ordY << endl ;
		}
};
int main() {
	Coord alan ; //declare an instance of the 'Coord' object called 'alan'
	alan.Results() ; //use the 'alan' object's 'Results()' method

	//declare another instance of the 'Coord' object called 'mary'
	Coord mary(17.623, 21.469) ; //overloading the constructor
	mary.Results();

	return 0;
}

Leave a Reply