Open In App

What is Destructor in Programming?

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In object-oriented programming, objects are the building blocks of our code, encapsulating data and behavior. When these objects are created, they often require resources like memory, file handles, or network connections, which are acquired through constructors. But what happens when these resources are no longer needed? If they aren’t properly released, they can lead to resource leaks, wasting valuable system resources and slowing down programs. This is where destructors come in. Destructors are special functions that automatically clean up resources when an object is no longer in use, ensuring efficient resource management.

In this article, we will learn what destructors are, how they work in different programming languages, and the best practices to follow when using them.

What is a Destructor?

A destructor is a member function of a class that is executed when an object of that class is destroyed. The purpose of a destructor is to free resources that were allocated to the object during its lifetime. Unlike constructors, which are called when an object is created, destructors are called when an object is destroyed.

Destructors are commonly used in resource management, where an object holds a resource such as dynamic memory, files, or network connections. Without a destructor, these resources could remain allocated even after the object is no longer needed, leading to resource leaks.

How Does a Destructor Work?

A destructor is automatically invoked when an object goes out of scope or is explicitly deleted. The steps involved in the destructor's operation are as follows:

  1. When an object goes out of scope, such as at the end of a function or block, or when the delete keyword is used on a dynamically allocated object, the destructor is triggered.
  2. The destructor is called, and the code within it is executed.
  3. After the destructor completes its execution, the object's memory is deallocated (in languages with manual memory management like C++) or marked for garbage collection (in languages like Java and C#).

Destructor in Different Programming Languages

The concept of destructors exists in several programming languages, but their implementation and behavior can vary. Let's see how destructors work in some common programming languages:

Destructor in C++

In C++, destructors are explicitly defined with the same name as the class, using the tilde (~) symbol before the class name. They are automatically called when an object goes out of scope or when delete is used on a pointer to an object.

Syntax of Destructor in C++

Below is the syntax of destructor when it is defined within the class.

class MyClass {
public:

// Destructor
~MyClass() {
// Code to clean up resources
}
};

Example

C++
// C++ program to demonstrate the usage of destructor in a class.
#include <iostream>
using namespace std;

class MyClass{
  public:
  
    // Constructor
    MyClass(){
        cout << "Constructor called!" << endl;
    }

    // Destructor
    ~MyClass(){
        cout << "Destructor called!" << endl;
    }
};

int main()
{
    // Constructor is called
    MyClass obj;

    // Destructor is called automatically when obj goes out of scope
    return 0;
}

Output
Constructor called!
Destructor called!

Destructor in Python

Python does not have explicit destructors like C++. Instead, Python uses a special method called __del__() also known as a destructor method in python that acts similarly to a destructor. It is called when all references to the object have been deleted i.e when an object is garbage collected. 

Syntax of Destructor in Python

class MyClass:

def __del__(self):
# Cleanup code

Note: A reference to objects is also deleted when the object goes out of reference or when the program ends. 

Example

Python
# Python program to demonstrate the usage of a destructor in a class.
class MyClass:
    def __init__(self):
        print("Constructor called!")

    def __del__(self):
        print("Destructor called!")

 # Constructor is called
obj = MyClass()

# Destructor is called
del obj

Output
Constructor called!
Destructor called!

Destructor in C#

In C#, destructors are called finalizers and are defined using the same syntax as in C++, but they are rarely used. C# relies on garbage collection to manage memory, and destructors are only needed for unmanaged resources.

Syntax of Destructor in C#

class MyClass {

// Rest of the class
// members and methods.

// Destructor (Finalizer)
~MyClass() {
// Cleanup code
}
}

Example

C#
// C# program to demonstrate the usage of destructor in a
// class.
using System;

class MyClass {
  
    // Constructor
    public MyClass(){
        Console.WriteLine("Constructor called!");
    }

    // Destructor (Finalizer)
    ~MyClass() { 
      Console.WriteLine("Destructor called!"); 
    }

    // A simple method to use the object
    public void DoSomething(){
        Console.WriteLine("Method DoSomething() called!");
    }
}

class Program {
    static void Main(){
        // Constructor is called
        MyClass obj = new MyClass();

        // Use the object to avoid the warning
        obj.DoSomething();

        // Destructor will be called automatically when the
        // program ends or object goes out of scope
    }
}

Output
Constructor called!
Method DoSomething() called!
Destructor called!

Destructor in PHP

In PHP, destructors are defined using the __destruct() method within a class. The destructor is automatically called when an object is no longer referenced or when the script ends.

Syntax of Destructor in PHP

class MyClass {     

// Destructor
public function __destruct() {
// destroying the object or clean up resources here
}
}

Example

PHP
<?php
// PHP program to demonstrate the usage of a constructor and destructor in a class.

class MyClass {
    // Constructor
    public function __construct() {
        echo "Constructor called!\n";
    }

    // Destructor
    public function __destruct() {
        echo "Destructor called!\n";
    }
}

// Create an object of MyClass
$obj = new MyClass();

// The destructor will be called automatically when the script ends or $obj goes out of scope
?>

Output
Constructor called!
Destructor called!

Languages Without Destructors

C

C does not have destructors because it is a procedural language without object-oriented features. In this resource management is handled manually using functions like malloc() for allocation and free() for deallocation.

JavaScript

JavaScript lacks destructors because it relies on automatic garbage collection. The engine automatically frees memory when objects are no longer in use and resources are managed using patterns like try...finally or event listeners.

Java

Java does not have traditional destructors. Instead, it uses garbage collection to manage memory. The deprecated finalize() method was previously used for cleanup, but in modern Java we use try-with-resources and the AutoCloseable interface for resource management.

Destructor vs. Constructor

While both constructors and destructors are special member functions, they serve opposite purposes:

FeatureConstructorDestructor
PurposeInitializes an objectCleans up resources used by an object
InvocationCalled automatically when an object is createdCalled automatically when an object is destroyed
ArgumentsCan take argumentsCannot take arguments
MultipleCan be overloaded (multiple constructors)Cannot be overloaded (only one destructor)
Return TypeNo return typeNo return type

Conclusion

Destructors play a important role in resource management and cleanup in object-oriented programming. While they are explicitly defined and used in languages like C++ and C#, other languages like Python and PHP provide alternative mechanisms for handling resource cleanup. Therefore, we need to understand how destructors work and when to use them for writing efficient and reliable code, especially in systems where manual resource management is required.


Next Article
Article Tags :

Similar Reads