C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Destructor in C++

In C++, a destructor is a special member function that gets executed automatically when an object goes out of scope or is explicitly deleted. Its main purpose is to release resources and perform cleanup tasks, such as deallocating memory, closing files, or releasing network connections.

In this tutorial, we'll cover how to define and use destructors in C++ classes.

  • Defining a Destructor: To define a destructor, you need to use the class name preceded by a tilde ~. A destructor doesn't take any parameters or return a value, and there can only be one destructor per class. The destructor is automatically called by the compiler when the object is destroyed.

Example:

#include <iostream>

class MyClass {
public:
    MyClass() {
        std::cout << "Constructor called." << std::endl;
    }

    ~MyClass() {
        std::cout << "Destructor called." << std::endl;
    }
};

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

Output:

Constructor called.
Destructor called.
  • Using Destructors for Resource Cleanup: Destructors are commonly used to release resources acquired by the object during its lifetime. This can help prevent memory leaks and ensure the proper release of resources.

Example:

#include <iostream>

class ResourceHolder {
public:
    int* data;

    ResourceHolder(int size) {
        data = new int[size];
        std::cout << "Resource allocated." << std::endl;
    }

    ~ResourceHolder() {
        delete[] data;
        std::cout << "Resource deallocated." << std::endl;
    }
};

int main() {
    {
        ResourceHolder holder(10);
    } // holder goes out of scope here

    std::cout << "End of the main function." << std::endl;

    return 0;
}

Output:

Resource allocated.
Resource deallocated.
End of the main function.
  • Notes on Destructors:
  • If you don't define a destructor explicitly, the compiler will automatically generate a default destructor. The default destructor will release the memory for the object itself, but it won't handle any custom resource cleanup tasks.
  • In inheritance scenarios, the destructor of the derived class is called first, followed by the destructor of the base class.
  • If a class has virtual functions, it's a good practice to make the destructor virtual as well. This ensures that the correct destructor is called when deleting objects through a base class pointer.

By using destructors in your C++ classes, you can ensure proper resource cleanup and prevent memory leaks. Remember to follow the guidelines for defining and using destructors to create more robust and maintainable code.

  1. How to implement a destructor in C++:

    • Description: Introduces the concept of destructors in C++ and demonstrates how to implement them for proper resource cleanup.
    • Example Code:
      class MyClass {
      public:
          // Destructor
          ~MyClass() {
              // Destructor body (cleanup code)
          }
      };
      
  2. Destructor for dynamic memory in C++:

    • Description: Illustrates how destructors are used for proper cleanup of dynamically allocated memory, preventing memory leaks.
    • Example Code:
      class DynamicMemoryObject {
      public:
          int* dynamicData;
      
          // Destructor for dynamic memory cleanup
          ~DynamicMemoryObject() {
              delete dynamicData;
          }
      };
      
  3. Virtual destructors in C++:

    • Description: Introduces virtual destructors and their importance in ensuring proper destruction of objects in polymorphic hierarchies.
    • Example Code:
      class Base {
      public:
          // Virtual destructor
          virtual ~Base() {
              // Destructor body
          }
      };
      
      class Derived : public Base {
      public:
          // Destructor (implicitly virtual due to the virtual destructor in the base class)
          ~Derived() {
              // Destructor body
          }
      };
      
  4. Destructor for objects with pointers in C++:

    • Description: Illustrates the use of destructors for objects that contain pointers, emphasizing proper cleanup to avoid memory leaks.
    • Example Code:
      class ObjectWithPointers {
      public:
          int* dynamicData;
      
          // Destructor for cleanup with pointers
          ~ObjectWithPointers() {
              delete dynamicData;
          }
      };