A destructor is another special class method, complimentary to a constructor, that cleans up resources by deleting the contents in the storage used for an object when it goes out of scope, or when the delete keyword is used on an object.


Has the same name as the class, preceded by a tilde ~

Has no return data type.

Takes no arguments.


Cannot be explicitly called. It is automatically called when the object goes out of scope.


If no destructor is defined, the compiler will automatically provide one for you. However, there might be time when you want to ensure the object has been cleaned, or you might want to carry out a quick exit task such as leaving a message.


#include <iostream>
using namespace std ;

class SingleValue{

	int myVar;

	SingleValue() ; //constructor prototype

	~SingleValue() { //destructor
		cout << "See ya later..." << endl ;

	void setValue(int) ;
	float getValue() ;
} ;

SingleValue::SingleValue(){ //constructor
	myVar = 0 ;
	cout << "Hello, World!" << endl ;

void SingleValue::setValue(int x){myVar = x ;}
float SingleValue::getValue(){return myVar ;}

int main () {

	SingleValue myValue ;

	myValue.setValue(42) ;

	cout << "myVar = " << myValue.getValue() << endl ;

	return 0;

Compile & Run:

Hello, World!
myVar = 42
See ya later...

Leave a Reply