What is a destructor in OOP?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

A destructor in Object-Oriented Programming (OOP) is a special method that is called when an object is destroyed or goes out of scope. The purpose of a destructor is to perform any necessary cleanup tasks, such as releasing resources (memory, file handles, network connections, etc.) that were acquired during the lifetime of the object.

Unlike constructors, which are used to initialize an object, destructors handle the cleanup when the object is no longer needed.

Key Characteristics of a Destructor

  • Automatically Called: A destructor is automatically invoked when an object is destroyed (typically when it goes out of scope or is explicitly deleted).
  • No Arguments and No Return Type: A destructor doesn't take any parameters and does not return any value.
  • Only One Destructor: A class can have only one destructor.
  • Cannot Be Overloaded: Unlike constructors, destructors cannot be overloaded.

Example of a Destructor in C++

In C++, destructors are commonly used to free dynamically allocated memory or resources that need to be explicitly released when the object is destroyed.

Example

#include <iostream> using namespace std; class Book { private: string title; string author; public: // Constructor Book(string t, string a) { title = t; author = a; cout << "Book \"" << title << "\" by " << author << " created." << endl; } // Destructor ~Book() { cout << "Book \"" << title << "\" by " << author << " destroyed." << endl; } }; int main() { { Book book1("1984", "George Orwell"); // Destructor will be called automatically when book1 goes out of scope } { Book book2("To Kill a Mockingbird", "Harper Lee"); // Destructor will be called automatically when book2 goes out of scope } return 0; }

Output:

Book "1984" by George Orwell created.
Book "1984" by George Orwell destroyed.
Book "To Kill a Mockingbird" by Harper Lee created.
Book "To Kill a Mockingbird" by Harper Lee destroyed.

In this example:

  • The constructor initializes the title and author of a Book object.
  • The destructor is automatically called when each object goes out of scope, and it outputs a message indicating the destruction of the object.

Why Use Destructors?

  • Memory Management: Destructors are often used to release dynamically allocated memory (for example, if you’ve used new or malloc to allocate memory).
  • Resource Cleanup: Destructors can also be used to release other resources like file handles, database connections, or network sockets.
  • Automatic Cleanup: In languages like C++, destructors are automatically invoked, making memory management easier and reducing the risk of memory leaks.

Destructor in Other Languages

  • C++: Destructors in C++ are denoted by a tilde (~) followed by the class name. They are invoked when an object is destroyed (e.g., when it goes out of scope or is explicitly deleted).

    ~ClassName() { /* cleanup code */ }
  • Java: Java does not have explicit destructors like C++. Instead, it uses garbage collection to manage memory. However, you can implement a method called finalize() (though it is deprecated in recent Java versions) to perform cleanup tasks.

  • Python: In Python, the equivalent of a destructor is the __del__() method, which is automatically called when an object is about to be destroyed by garbage collection.

    class Book: def __init__(self, title, author): self.title = title self.author = author def __del__(self): print(f"Book \"{self.title}\" by {self.author} is being destroyed.")

To deepen your understanding of destructors and other OOP concepts, consider enrolling in the following courses from DesignGurus.io:

These courses offer comprehensive insights and practical examples to help you master Object-Oriented Programming principles and excel in your technical interviews.

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Why are algorithms used in interviews?
Are non-functional requirements the same as technical requirements?
Comprehensive review sessions to identify and fix skill gaps
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.