What is Destructor in Programming?
Last Updated :
13 Aug, 2024
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:
- 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.
- The destructor is called, and the code within it is executed.
- 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:
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;
}
OutputConstructor called!
Destructor called!
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
OutputConstructor called!
Destructor called!
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
}
}
OutputConstructor called!
Method DoSomething() called!
Destructor called!
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
?>
OutputConstructor 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:
Feature | Constructor | Destructor |
---|
Purpose | Initializes an object | Cleans up resources used by an object |
Invocation | Called automatically when an object is created | Called automatically when an object is destroyed |
Arguments | Can take arguments | Cannot take arguments |
Multiple | Can be overloaded (multiple constructors) | Cannot be overloaded (only one destructor) |
Return Type | No return type | No 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.
Similar Reads
What are Objects in Programming?
In object-oriented programming (OOP), objects are the basic entities that actually exists in the memory. Each object is based on a blueprint of attributes and behaviours (variables and functions) defined as Class. The basic purpose of a Class is to identify the common attributes and behaviours and g
2 min read
What are Operators in Programming?
Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types. Operators in Programming Table of
15+ min read
Error Handling in Programming
In Programming, errors occur. Our code needs to be prepared for situations when unexpected input from users occurs, division by zero occurs, or a variable name is written incorrectly. To prevent unexpected events from crashing or having unexpected outcomes, error handling involves putting in place m
12 min read
What is Parameter Destructuring in TypeScript ?
Parameter destructuring in TypeScript is a way to extract values from objects or arrays passed as function parameters, making it easier to work with their properties or elements directly within the function body. There are several methods through which parameter destructuring is achieved in TypeScri
3 min read
Destructors in Python
Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
7 min read
What is __del__ in Python?
In Python, object-oriented programming provides several special methods that start and end with double underscores, known as "magic methods" or "dunder methods." These methods enable you to customize the behavior of your classes in specific ways. One such method is __del__, which is also known as th
4 min read
What is Data Destruction?
Data Destruction is a software-based method of data sanitization that aims to fully destroy all electronic data stored on a hard disk drive or other digital media by overwriting data onto all areas of the device in an irreversible process. In data destruction, the data remains on the memory chip or
6 min read
Unary Operators in Programming
In programming, operators act as powerful tools for manipulating data and performing various operations. Among these, unary operators stand out, functioning on a single operand to transform or evaluate data in different ways. This post explains the types, implementations, and best practices associat
9 min read
What is Constructor?
A constructor is a special type of method used in object-oriented programming languages to initialize objects. The constructor is called automatically every time when an object is created, allowing the object to set initial values for its attributes or perform other setup tasks.In this article, we w
3 min read
What is D Programming Language: Usage and Applications
The D programming language is another powerful high-performance language designed for effective programming of system-level and application software. Combining the efficiency of C++ with the simplicity of modern languages like Python, D attempts to provide a productive experience without applying an
8 min read