Understanding Destructors In C++ (OOP)

Understanding Destructors In C++ (OOP)

In object-oriented programming, every object has a life cycle. It is created, it performs certain tasks, and eventually it is destroyed. While much attention is given to how objects are created using constructors, equal importance must be given to how objects are destroyed.

In C++, the destruction of an object is handled by a special member function called the destructor.

A destructor ensures that when an object completes its purpose, the resources associated with it are released in a controlled and safe manner.

Definition of Destructor

A destructor is a special member function of a class that is automatically invoked when an object goes out of scope or is deleted.

Its name is the same as the class name but is preceded by a tilde (~) symbol.

General Form:

~ClassName();

Characteristics of a destructor:

  • It has the same name as the class.
  • It begins with the symbol ~.
  • It does not take any parameters.
  • It does not return any value.
  • A class can have only one destructor.
Destructor

Understanding Destructor Through an Example

Let us study the concept using the following class.

#include <iostream>
using namespace std;

class Student {
    private:
        string rollnum; // Private member: Roll number of the student.

    public:
        string name; // Public member: Name of the student.

        // Constructor
        Student(string r, string n) : rollnum(r), name(n) {}

        // Destructor
        ~Student() {
            cout << "Destructor is called" << endl;
        }

        // Public Function
        void show() {
            cout << "The name of Student is: " << name << endl;
            cout << "The roll number of Student is: " << rollnum << endl;
        }
};

Now consider the main() function:

int main() {
    Student s1("SE-101", "Ali");
    s1.show();
    return 0;
}

Step-by-Step Execution

When the program executes:

  1. The object s1 is created.
  2. The constructor runs automatically and displays:
    Student data open
  3. The function show() displays the student’s name and roll number.
  4. When the main() function ends, the object s1 goes out of scope.
  5. The destructor runs automatically and displays:
    Destructor is called

This clearly demonstrates that destructors are invoked automatically when the object’s lifetime ends.

Why Is the Destructor Important Here?

In this simple example, the destructor only prints a message. However, in real-world applications, a destructor performs critical tasks such as:

  • Releasing dynamically allocated memory
  • Closing open files
  • Terminating network connections
  • Releasing database handles
  • Freeing system resources

Even though the Student class does not allocate dynamic memory, the destructor is still part of the class design to demonstrate object destruction.

In professional programming, ignoring destructors can lead to memory leaks and unstable systems.

Object Lifetime and Scope

One of the most important concepts connected to destructors is scope.

An object created inside a block is destroyed when the block ends.

int main() {
    {
        Student s1("SE-102", "Sara");
        s1.show();
    }   // Destructor called here

    cout << "Outside block" << endl;
}

As soon as the inner block finishes, the destructor of s1 is executed before the program continues.

This automatic cleanup mechanism makes C++ powerful and reliable.

Order of Destructor Calls

If multiple objects are created inside a function, destructors are called in reverse order of their creation.

Destructor Order (LIFO)
int main() {
    Student s1("SE-201", "Ahmed");
    Student s2("SE-202", "Hina");
}

Execution order:

  1. Constructor of s1
  2. Constructor of s2
  3. Destructor of s2
  4. Destructor of s1

This behavior follows the principle of Last In, First Out (LIFO).

Destructor and Dynamic Objects

If an object is created using dynamic memory allocation, the destructor will only run when delete is used.

int main() {
    Student* ptr = new Student("SE-303", "Bilal");
    ptr->show();
    delete ptr;  // Destructor called here
}

If delete is not used, the destructor will not execute, and the memory will remain allocated. This causes a memory leak.

Constructor vs Destructor

ConstructorDestructor
Initializes the objectCleans up the object
Same name as classSame name with ~
Can be overloadedCannot be overloaded
Executes at creationExecutes at destruction

The constructor prepares the object for use.
The destructor ensures the object leaves the system safely.

Conceptual Understanding

Every object in C++ has a beginning and an end.

  • The constructor marks the beginning of the object’s life.
  • The destructor marks the end of the object’s life.

Even if we do not explicitly define a destructor, C++ provides a default destructor automatically. However, when resources must be released manually, defining a destructor becomes essential.

A destructor reflects responsibility in programming.

When we design a class, we must think not only about how the object will work, but also about how it will be properly destroyed.

A well-written destructor ensures:

  • Clean memory management
  • Safe execution
  • Professional program design

Leave a Reply

Your email address will not be published. Required fields are marked *