Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
🟣 OOP  ·  Lesson 40

Destructors in C++

Written and reviewed by · Senior IT Faculty · 15+ years’ experience

What is a destructor?

A destructor is the opposite of a constructor: it runs automatically when an object is destroyed, giving it a chance to clean up — free memory, close files, release resources. Its name is the class name with a leading ~, and it takes no arguments.

Syntax and example

C++
#include <iostream>
using namespace std;
class Logger {
public:
    Logger()  { cout << "Created\n"; }   // constructor
    ~Logger() { cout << "Destroyed\n"; } // destructor
};
int main() {
    Logger l;          // "Created"
    cout << "Working...\n";
    return 0;          // "Destroyed" runs here
}
Output:
Created
Working...
Destroyed

When is it called?

  • When a local object goes out of scope (its block ends).
  • When a heap object is deleted.
  • When the program ends, for objects still alive.

Local objects are destroyed in the reverse order they were created.

Freeing resources

The classic use is releasing memory a class allocated with new:

C++
class Buffer {
    int *data;
public:
    Buffer(int n) { data = new int[n]; }   // acquire
    ~Buffer()     { delete[] data; }       // release
};

Because the destructor runs automatically, the memory is freed even if you forget — as long as the object is destroyed.

RAII and the rule of three

RAII — Resource Acquisition Is Initialization — is the C++ idea of tying a resource's lifetime to an object: acquire in the constructor, release in the destructor. It makes cleanup reliable even when errors happen.

The rule of three: if your class needs a custom destructor, it usually also needs a custom copy constructor and copy assignment operator, since all three deal with managing the resource. Modern C++ often avoids this entirely by using smart pointers.

Common mistakes

  • Forgetting the ~, so it looks like a constructor.
  • Giving a destructor parameters or a return type (it has neither).
  • Needing a custom destructor but ignoring the rule of three (double free).
  • Manually managing memory when a smart pointer would handle it automatically.
🏋️ Practice

Write a class whose constructor prints "Opening" and destructor prints "Closing". Create two objects in a block and watch the order of construction and destruction. Then create one with new and delete it.

Summary

  • A destructor runs automatically when an object is destroyed.
  • Named ~ClassName(), with no arguments or return type.
  • Called at end of scope, on delete, or at program end (reverse order).
  • Used to free memory and release resources — the basis of RAII.
  • A custom destructor usually means you need the rule of three.

Frequently Asked Questions

What is a destructor in C++?
A destructor is a special member function that runs automatically when an object is destroyed, used to release resources the object was holding, such as memory or files. It has the class name preceded by a tilde, like ~Car(), takes no arguments and returns nothing.
When is a destructor called in C++?
A destructor runs automatically when an object goes out of scope, when a dynamically allocated object is deleted, or when a program ends. For local objects this happens at the closing brace of their block, in reverse order of creation.
Why are destructors important in C++?
Destructors let an object clean up after itself — freeing heap memory, closing files, or releasing other resources — so you do not leak them. This automatic cleanup is the basis of RAII, a core C++ technique for safe resource management.
What is RAII in C++?
RAII (Resource Acquisition Is Initialization) means an object acquires a resource in its constructor and releases it in its destructor. Because the destructor always runs when the object is destroyed, resources are freed reliably even if an error occurs.
What is the rule of three in C++?
The rule of three says that if a class needs a custom destructor, it usually also needs a custom copy constructor and copy assignment operator, because managing a resource by hand affects all three. Ignoring it can lead to double frees or leaks.

Destructor क्या है?

Destructor constructor का उल्टा है: यह object नष्ट होने पर अपने आप चलता है, उसे सफ़ाई का मौका देते हुए — memory मुक्त करना, files बंद करना, resources छोड़ना। इसका नाम class के नाम के आगे ~ के साथ होता है, और यह कोई arguments नहीं लेता।

Syntax और उदाहरण

C++
#include <iostream>
using namespace std;
class Logger {
public:
    Logger()  { cout << "Created\n"; }   // constructor
    ~Logger() { cout << "Destroyed\n"; } // destructor
};
int main() {
    Logger l;          // "Created"
    cout << "Working...\n";
    return 0;          // "Destroyed" yahan chalta hai
}
Output:
Created
Working...
Destroyed

यह कब call होता है?

  • जब कोई local object scope से बाहर जाता है (उसका block समाप्त होता है)।
  • जब heap object delete होता है।
  • जब program समाप्त होता है, अब भी जीवित objects के लिए।

Local objects बनने के उल्टे क्रम में नष्ट होते हैं।

Resources मुक्त करना

Classic इस्तेमाल है वह memory छोड़ना जो class ने new से allocate की:

C++
class Buffer {
    int *data;
public:
    Buffer(int n) { data = new int[n]; }   // acquire
    ~Buffer()     { delete[] data; }       // release
};

चूँकि destructor अपने आप चलता है, memory मुक्त होती है भले आप भूल जाएँ — जब तक object नष्ट हो।

RAII और rule of three

RAII — Resource Acquisition Is Initialization — किसी resource के जीवनकाल को object से बाँधने का C++ विचार है: constructor में लो, destructor में छोड़ो। यह सफ़ाई को भरोसेमंद बनाता है भले errors हों।

Rule of three: अगर आपकी class को custom destructor चाहिए, तो आमतौर पर उसे custom copy constructor और copy assignment operator भी चाहिए, क्योंकि तीनों resource प्रबंधन से जुड़े हैं। आधुनिक C++ अक्सर smart pointers इस्तेमाल करके इससे पूरी तरह बचता है।

आम गलतियाँ

  • ~ भूलना, तो यह constructor जैसा दिखता है।
  • Destructor को parameters या return type देना (इसके पास कोई नहीं)।
  • Custom destructor चाहिए पर rule of three अनदेखा करना (double free)।
  • Memory हाथ से प्रबंधित करना जब smart pointer इसे अपने आप संभालता।
🏋️ अभ्यास

एक class लिखें जिसका constructor "Opening" और destructor "Closing" print करे। एक block में दो objects बनाएँ और construction तथा destruction का क्रम देखें। फिर एक को new से बनाएँ और delete करें।

सारांश

  • Destructor object नष्ट होने पर अपने आप चलता है।
  • ~ClassName() नामित, बिना arguments या return type।
  • Scope के अंत में, delete पर, या program अंत में call होता है (उल्टा क्रम)।
  • Memory मुक्त करने और resources छोड़ने को इस्तेमाल — RAII का आधार।
  • Custom destructor का मतलब आमतौर पर आपको rule of three चाहिए।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.