[C++] What is a Destructor? | Automatic Cleanup When an Object is Destroyed

目次

Introduction

Just as a C++ constructor is an initialization process called automatically the moment an object is “born,” a Destructor is a special member function called automatically just before an object “vanishes” from memory to perform cleanup.

The main role of a destructor is to safely return resources used by the object, such as memory or file handles, to the program. This helps prevent problems like memory leaks before they happen.

In this article, I will explain the basic definition of a destructor and the timing at which it is called in an easy-to-understand manner.

Destructor Definition Rules

Like constructors, destructors have strict rules.

  • The function name must be the class name preceded by a tilde (~).
  • It must not have a return type (not even void).
  • It cannot take any arguments.
  • You cannot define multiple destructors (overloading is not possible) in a single class.

Sample Code Using a Destructor

This code defines a constructor and a destructor in the MyObject class and tracks when the object is created and when it is destroyed upon exiting the scope.

Complete Code

#include <iostream>
#include <string>

using namespace std;

class MyObject {
public:
    string name;

    // Constructor
    MyObject(string n) {
        name = n;
        cout << "Constructor: Object '" << name << "' created." << endl;
    }
    
    // Destructor
    ~MyObject() {
        cout << "Destructor: Object '" << name << "' destroyed." << endl;
    }
};

// Scope of testFunction
void testFunction() {
    cout << "--- Starting testFunction ---" << endl;
    MyObject obj_in_func("Object inside function");
    cout << "--- Ending testFunction ---" << endl;
    // The scope of obj_in_func ends here, so the destructor is called.
}

// Scope of main function
int main() {
    cout << "--- Starting main function ---" << endl;
    
    testFunction(); // Call the function
    
    MyObject obj_in_main("Object inside main");
    cout << "--- Ending main function ---" << endl;
    
    return 0;
    // The scope of obj_in_main ends here, so the destructor is called.
}

Execution Result

--- Starting main function ---
--- Starting testFunction ---
Constructor: Object 'Object inside function' created.
--- Ending testFunction ---
Destructor: Object 'Object inside function' destroyed.
Constructor: Object 'Object inside main' created.
--- Ending main function ---
Destructor: Object 'Object inside main' destroyed.

Code Explanation

~MyObject()

This is the definition of the destructor. The tilde ~ is attached before the class name MyObject. There are no arguments or return values.

Timing of Destructor Invocation

The destructor is automatically called when the object’s “scope” ends. Scope refers to the range where that variable is valid.

  • obj_in_func: Declared inside the {} of testFunction. When testFunction ends at }, it leaves the scope, and the destructor is called.
  • obj_in_main: Declared inside the main function. When the main function ends at }, it leaves the scope, and the destructor is called.

Looking at the output order of the execution result, you can clearly see that the constructor is called when the object is generated, and the destructor is called when that object leaves its valid range.

new and delete

For objects where memory is dynamically allocated using the new operator, they are not automatically destroyed even if the scope ends. The destructor is executed only when the delete operator is explicitly called.

Summary

In this article, I explained the basic role and usage of destructors in C++.

  • A destructor is a cleanup function called automatically just before an object is destroyed.
  • The function name is ~ClassName, and it has no arguments or return values.
  • Its main purpose is to release resources such as memory used by the object.

While you don’t often need to explicitly write a destructor for simple classes, its role becomes extremely important when designing classes that require cleanup, such as releasing memory allocated with new.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次