Back to C++
2026-02-135 min read

C++ Destructors

Learn C++ Destructors step by step with clear examples and exercises.

Why This Matters

Welcome to this detailed guide on C++ destructors! This lesson will help you understand why destructors are essential, their prerequisites, and how to use them effectively. We'll also discuss common mistakes, practice questions, and frequently asked questions to ensure you have a solid grasp of this topic.

Why This Matters

Destructors in C++ play a crucial role in managing the lifetime of objects. They are called when an object goes out of scope or is deleted explicitly. Proper use of destructors ensures that any resources allocated by the object, such as memory and file handles, are properly deallocated to avoid memory leaks and other issues. Destructors are particularly important in real-world applications where objects can have complex lifetimes and resource management requirements.

Prerequisites

Before diving into destructors, you should be familiar with the following concepts:

  1. C++ basics, including classes, objects, and constructors
  2. Understanding of object lifetime and scope rules
  3. Basic memory allocation and deallocation using new and delete
  4. Exception handling in C++ (optional but recommended)

Core Concept

A destructor is a special member function of a class that gets called automatically when an object of its class goes out of scope or is explicitly deleted using the delete operator. The destructor name is the class name preceded by a tilde (~). For example, if you have a class named MyClass, its destructor would be ~MyClass().

Destructors are used to clean up any resources allocated by the object during its lifetime. This includes deallocating memory, closing files, and releasing other system resources. Destructors are called in the reverse order of construction when an object goes out of scope or is deleted explicitly.

Default Destructor

If you don't explicitly declare a destructor for your class, C++ will automatically generate a default destructor for you. However, the default destructor does not perform any cleanup tasks and should be overridden if your class manages resources that need to be deallocated.

User-Defined Destructors

To define a custom destructor, simply declare a function with the destructor signature (~ClassName()) within the class definition. Here's an example:

class MyClass {
public:
// Constructor
MyClass(int data) : m_data(data) {}

// Destructor
~MyClass() {
std::cout << "Destructor called for object with data: " << m_data << std::endl;
}

private:
int m_data;
};

In this example, we have defined a destructor that prints the value of the m_data member variable when the object is destroyed.

Destructor Call Order

Destructors are called in the reverse order of construction when an object goes out of scope or is deleted explicitly. This means that if you have a class with multiple objects, and one of those objects contains another object, the inner object's destructor will be called before the outer object's destructor.

Worked Example

Let's create a simple example to demonstrate the use of destructors:

#include <iostream>
using namespace std;

class MyClass {
public:
// Constructor
MyClass(int data) : m_data(data) {}

// Destructor
~MyClass() {
cout << "Destructor called for object with data: " << m_data << endl;
}

private:
int m_data;
};

int main() {
MyClass obj1(10);
MyClass obj2(20);

// Explicit deletion of obj1, causing its destructor to be called
delete &obj1;

return 0;
}

In this example, we create two objects obj1 and obj2. When the program ends, both objects go out of scope, and their destructors are called. However, we explicitly delete obj1, causing its destructor to be called before the program ends. The output will be:

Destructor called for object with data: 10
Destructor called for object with data: 20

Common Mistakes

  1. Not defining a destructor when necessary: If your class manages resources that need to be deallocated, you must define a custom destructor to ensure proper cleanup.
  1. Forgetting to call the base class destructor in derived classes: When overriding a destructor in a derived class, don't forget to call the base class destructor using base::::~BaseClass() to ensure proper destruction of the base class sub-object.
  1. Returning values from destructors: Destructors should not return any value. They are called automatically and should focus solely on cleanup tasks.
  1. Destructor calls during construction: Destructors should only be called when an object goes out of scope or is explicitly deleted. Calling a destructor during construction can lead to undefined behavior.

Practice Questions

  1. Write a class MyString that manages a dynamically allocated character array. Define a constructor, a destructor, and appropriate member functions for creating, copying, and concatenating strings.
  1. Implement a derived class DerivedClass from the base class BaseClass. Override the destructor in DerivedClass to print a message indicating that the derived class object is being destroyed. Ensure proper destruction of the base class sub-object by calling its destructor.

FAQ

  1. Can I call a constructor within a destructor? No, it's not possible to call a constructor from a destructor because constructors are used for initialization, and destructors are called during object destruction.
  1. What happens if a destructor throws an exception? If a destructor throws an exception, the program will terminate immediately due to the uncaught exception. This is known as a stack unwind and can be handled using exception specifications (Rtti) or a custom exception handler.
  1. Can I have multiple destructors for the same class? No, C++ does not allow multiple destructors for the same class. However, you can overload constructors to create different versions based on the number and type of arguments.
  1. What is the purpose of a default destructor? The default destructor is automatically generated by the compiler when no user-defined destructor exists. It performs no cleanup tasks but can be overridden if necessary.
C++ Destructors | C++ | XQA Learn