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. 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:

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
A value to a variable int a = 250;
The value of one variable to another NbrOfBoys = NbrOfGirls;
A value to an object’s member Video.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

  1. To illustrate the construction and destruction effects of an object, create a new Console Application named Library
  2. Change the content of the file as follows:
  3. Execute the program to see the result:
  4. Return to your programming environment
  5. Reopen the Students project from the Students2 folder.
  6. To create a destructor for our TStudent class, change the header file as follows:
  7. Implement the destructor in the Students.cpp file as follows:
  8. Test the program and return to your programming environment.