destructors in c++

A destructor is another special kind of class member function that is executed when an object of that class is destroyed. They are the counterpart to constructors. When a variable goes out of scope, or a dynamically allocated variable is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to help clean up the class before it is removed from memory. For simple classes, a destructor is not needed because C++ will automatically clean up the memory for you. However, if you have dynamically allocated memory, or if you need to do some kind of maintenance before the class is destroyed (eg. closing a file), the destructor is the perfect place to do so.
Like constructors, destructors have specific naming rules:

  • The destructor must have the same name as the class, preceded by a tilde (~).
  • The destructor can not take arguments.
  • The destructor has no return type.

Consider the following example :

#include <iostream>
using namespace std;

class letsDrive
		cout << "please start engine" << endl;

	void carEngineStarted()
		cout << "Please accelerate, Happy journey" << endl;

	void carDriving()
		cout << "going at 40 mph " << endl;
	void afteroneHour()
		cout << "I reached destination" << endl;
	void movedOutOfCar()
		cout << "I moved out of car" << endl;

	~letsDrive() // destructor
		cout << "car engine off automatically. Bye......" << endl;

int main()
	letsDrive myself;
	return 0;

Output :

please start engine
Please accelerate, Happy journey
going at 40 mph
I reached destination
I moved out of car

car engine off automatically. Bye......