AppDividend
Latest Code Tutorials

C++ Destructor Example | Destructors in C++ Tutorial

0

C++ Destructor Example | Destructors in C++ Tutorial is today’s topic. Destructor is the member function which destructs or deletes an object. A destructor function is called automatically when an object goes out of scope: (1) the function ends. (2) the program ends. (3) a block containing local variables ends. (4) A delete operator is called. We have already seen Constructor in C++ on this blog.

C++ Destructor

Destructor is the special member function that automatically deletes or destructs an object (instance of a class) to release memory or close a file when it goes out of its scope.

A destructor is called when:

  1. Termination of a program: When the object is declared with a global scope or with static class, a destructor is executed automatically when the program ends to clear up the memory taken by that object.
  2. The flow of control out of a block: In the case where objects are defined with local scope in a specific block, the destructor is called when the execution control gets out of that particular block, then be it a function, loop or condition.
  3. Delete function: When the delete function is executed/called for a particular data member, then the destructor for that object is called immediately, even if the memory isn’t deallocated. See the following syntax. delete data_member;
  4.  Explicit destructor call: Sometimes it is necessary to explicitly call a destructor in order to clean up resources at absolute addresses which may not be possible with delete operator because that memory was never allocated from free space.

See the following syntax.

object_name.class_name ::~class_name();

#Program to declare Destructors

See the following program.

#include <iostream>
using namespace std;
class apple {
    public:
    int roll;
    apple(){       //Constructor
        roll=5;
        cout << "Roll is " << roll << endl;
    };
    ~apple(){      //Destructor
        roll=-5;
        cout << "Roll is " << roll << endl;
    };
};
int main(){
    apple obj1;
    return 0;
}

See the following output.

 

C++ Destructor

#Rules for declaring a destructor

  1. It is defined with the same name as the class name preceded by the tilde operator (~).
  2. It does not contain any arguments or parameters.
  3. It does not return any value (not even void).
  4. There can be only one destructor in a specific class.

#Need to declare a destructor explicitly

While the compiler itself provides a default destructor, it is good to declare a destructor yourself when :

  1. Using dynamic memory allocation functions in the program.
  2. You are using pointers/referencing to access data members.

If default destructor is used in the above cases, it can cause memory leakage where the object’s memory may not be freed up even after the completion of program execution.

#Order of destruction

#Virtual Base Classes

In case of virtual base classes, i.e., classes whose functions and member variables can be overridden and redefined by subclasses of an outer class, the destructor runs in reverse order in the inheritance graph.

Therefore, it starts with the bottom last child class and goes to the top from the extreme left towards the right following every possible path. So, as to create a list of classes having all unique elements and containing all of them.

See the following syntax.

class a;
class b;
class c : virtual public a, virtual public b;
class d : virtual public a, virtual public b;
class e : public c, public d, virtual public b;

For, the above declaration the list goes as like,

Non-virtual class e
Non-virtual class d
Non-virtual class c
Virtual class b
Virtual class a

#Non-Virtual Base Classes

With non-virtual classes, the destructor runs according to the order in which the class names are used when declaring the child class. It goes in the reverse order, i.e., starting from the right towards the left in the statement declaring the child class.

See the following example.

class child : public parent1, public parent2

In this case, the destructor for the parent2 class is executed first and then the destructor for parent1.

#How destructors are different from a regular member function

  1. Destructors have a same name as the class preceded by a tilde (~).
  2. Destructor doesn’t take any argument and doesn’t return anything.

#Can we have more than one destructor in a class?

No, there can only one destructor in the class with class name preceded by ~(tilde), no parameters, and no return type.

#When do we need to write the user-defined destructor?

If we do not write our destructor in the class, the compiler creates the default destructor for us. A default destructor works fine unless we have dynamically allocated the memory or pointer in the class. When the class contains a pointer to a memory allocated in the class, we should write the destructor to release memory before a class instance is destroyed. It must be done to avoid the memory leak.

#Can a destructor be virtual?

Yes, it is always a good idea to make destructors virtual in base class when we have a virtual function. See virtual destructor for more details.

#Virtual Destructor

Deleting the derived class object using the pointer to a base class that has non-virtual destructor results in the undefined behavior. If we want to correct this situation, the base class should be defined with the virtual destructor. 

Making base class destructor virtual guarantees that an object of the derived class is destructed correctly, i.e., both base class and derived class destructors are called.

So, here we end the article of C++ Destructor tutorial with example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.