🧱 C++ Object-Oriented Programming
Estimated reading: 3 minutes 274 views

C++ Destructors – Object Cleanup and Resource Management


Introduction – Why Destructors Matter in C++

In C++ programming, a destructor is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. Its main purpose is to release resources, such as memory or file handles, that were acquired during the lifetime of the object.

In this guide, you’ll learn:

  • What destructors are and how they work
  • Syntax and use cases
  • When destructors are called
  • Best practices for safe cleanup

What Is a Destructor?

A destructor:

  • Has the same name as the class preceded by a tilde ~
  • No return type and no parameters
  • Automatically called when the object dies (scope ends or delete is called)

Code Examples – With Output

Example 1: Basic Destructor Behavior

#include <iostream>
using namespace std;

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

int main() {
    MyClass obj;
    return 0;
}

Output:

Constructor called!
Destructor called!

Explanation:

  • Constructor is called when object obj is created
  • Destructor is automatically called when main() ends and obj goes out of scope

Example 2: Destructor with Dynamic Memory

#include <iostream>
using namespace std;

class Data {
    int* ptr;

public:
    Data() {
        ptr = new int;
        cout << "Memory allocated!" << endl;
    }

    ~Data() {
        delete ptr;
        cout << "Memory released!" << endl;
    }
};

int main() {
    Data d;
    return 0;
}

Output:

Memory allocated!
Memory released!

Explanation:

  • Memory is allocated in the constructor
  • Destructor ensures it is properly released

Destructor Characteristics

FeatureDescription
NameSame as class, prefixed with ~
Parameters No
Return Type None
Overloading Allowed No
Automatically Called Yes, on scope end or delete
Use in Inheritance Supports virtual destructors

Virtual Destructors – For Safe Polymorphism

class Base {
public:
    virtual ~Base() {
        cout << "Base destructor called" << endl;
    }
};

class Derived : public Base {
public:
    ~Derived() {
        cout << "Derived destructor called" << endl;
    }
};

int main() {
    Base* b = new Derived();
    delete b;
    return 0;
}

Output:

Derived destructor called
Base destructor called

Tip: Always use a virtual destructor in base classes if they are meant to be inherited.


Best Practices & Tips

Best Practice: Always free dynamically allocated memory in destructors.

Tip: Use smart pointers like std::unique_ptr or std::shared_ptr to automate cleanup.

Pitfall: Avoid throwing exceptions in destructorsβ€”it can lead to undefined behavior if another exception is active.


Use Cases for Destructors

Memory Cleanup: delete dynamically allocated memory
File Handling: Close file streams or database connections
Thread Locks: Release locks, semaphores, or mutexes
General Cleanup: Unsubscribe events, disconnect sockets, etc.


Summary – Recap & Next Steps

Key Takeaways:

  • Destructors clean up resources automatically
  • They are called when the object’s lifetime ends
  • Use virtual destructors for base classes with inheritance

Real-World Relevance:
Used in system libraries, networking classes, file/resource wrappers, and container classes to prevent memory leaks.

Next Steps:

  • Learn about Initialization Lists & Dynamic Initialization
  • Explore Smart Pointers for Safer Resource Management

FAQ – C++ Destructors

Is a destructor mandatory in C++?
No. If you don’t define one, the compiler generates a default destructor.

Can a destructor be overloaded?
No. Only one destructor is allowed per class.

Can I call a destructor explicitly?
Yes, but not recommended unless you’re using placement new. Normally, delete or scope exit handles this.

What happens if I forget to free memory in the destructor?
You’ll create a memory leak. Always release acquired resources.

Should destructors be virtual in base classes?
Yes, if you intend to delete derived objects using a base class pointer.


Share Now :
Share

C++ Destructors

Or Copy Link

CONTENTS
Scroll to Top