As opposed to a constructor, a destructor is called when a program has finished using an instance of an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always create a default destructor if you don’t create one. Like the default constructor, a destructor also has the same name as its object. This time, the name of the destructor starts with
a tilde.

To create your own destructor, in the header file, type ~ followed by the name of the object. We use #ifndef directive to define the class. Here is an example:

As done with a default constructor, you don’t need to put anything in the implementation of a destructor. In fact, when a program terminates, the compiler can itself destroy all of the objects and variables that your program has used. The only true time you will be concerned with destroying objects is if the objects were created dynamically, which we will learn when studying pointers.

You can implement your destructor in the header file by just providing it with empty parentheses:

Otherwise, you can also implement it in the cpp file with empty parentheses. Here is an example:

Having difficulties understanding the code and output then you can get coding help and dive into expert knowledge and support tailored to your programming needs.

The Copy Constructor

Copying an Object

After creating an object and assigning appropriate values to its members, you can perform any regular operation on it. Although this gets a little particular with objects, which will be expanded when learning about operator overloading, you can assign an object to another object. We have already learned:

How to
assign
Example
A value to a variableint a = 250;
The value of one variable to anotherNbrOfBoys = NbrOfGirls;
A value to an object’s memberVideo.Category = ‘Drama’

Assigning a variable to another is equivalent to making a copy of that variable. As you assign a variable to another, you can assign one object to another. Both objects must be recognizably equivalent to the compiler. Imagine you want to build the same brick twice. All you have to do is to assign one brick to another, which is take care of in the following main() function:

Here is an example of running the program:

Notice that both orders display the same thing.

Using Destructors

To illustrate the construction and destruction effects of an object, create a new Console Application named Library

Change the content of the file as follows:

Execute the program to see the result:

Return to your programming environment

Reopen the Students project from the Students2 folder.

To create a destructor for our TStudent class, change the header file as follows:

Implement the destructor in the Students.cpp file as follows:

Test the program and return to your programming environment.