Destructor in C++

Destructor

Destructor is a special member function that always executes when compiler is destroying an object. It is used to free allocated memory, close and dispose used resources and for any other things which we want to execute before destroy an object.

The name of the destructor starts with tilde (~) followed by the name of the class. Destructor does not have any parameters. Here is an example of a destructor for person class:

Person::~Person()
{
	cout << "Destructor called for " << firstName << " object" << endl;
}

During this topic, we created three objects:

Person person1;//declare a person
//use constructor with 3 parameters
Person person2("Smith", "James", 1992);
person2.print();

Person person3("Green", "Alan");
person3.print();

Execute this program. Destructor will be called for all the created objects:

Default constructor is starting

Constructor with 3 parameters is starting

First name Smith

Last name James

Year of Birth 1992

Constructor with 3 parameters is starting

First name Green

Last name Alan

Year of Birth 1990

Destructor called for Green object

Destructor called for Smith object

Destructor called for  object

Last line “Destructor called for object” do not specify any name, because person1 was created by using default constructor. As you can see, destructors are called in back order relatively to the order of objects created. The first created object is destroyed last. And the last created object is destroyed first.

Translate »