Destructors in C++

Lesson Introduction

Hello! Today, we are going to learn about a special type of function in C++ called a destructor. Destructors play a crucial role in managing resources, like memory, in programming. If you've ever played with toys and had to clean up, think of a destructor as the tool that helps clean up after the objects your program uses. By the end of this lesson, you'll understand what destructors are, how to use them, and why they're important.

Understanding Destructors

In C++, a destructor is a special member function of a class that runs when an object of that class goes out of scope or is explicitly deleted. Imagine you have a paper airplane, and when you're done playing with it, you need to recycle the paper. A destructor helps with that recycling process in programming.

Destructors are vital because they ensure that resources, like memory or files, are properly released. This prevents memory leaks.

Destructor Syntax

A destructor has the same name as the class but is preceded by a tilde (~). It doesn't take any arguments and doesn't return any value. Additionally, a class can only have one destructor, you can't overload it.

Here's a simple example:

class MyClass {
public:
    // Constructor
    MyClass() {
        // Constructor code
    }

    // Destructor
    ~MyClass() {
       // Destructor code
    }
};

This class MyClass has a constructor (to set up the object) and a destructor (to clean up the object). If you don't define a destructor, the compiler provides a default one. However, it's a good practice always to declare your own destructor if your class manages resources like dynamic memory, file handles, or network connections. This ensures that resources are correctly and explicitly released.

You can also define the destructor outside the class, just like with other methods:

// Destructor implementation outside the class
MyClass::~MyClass() {
    // Destructor code
}

Destructors in Action

Let's explore how destructors work with a practical example. We will create a class called MyClass, and our program will print messages when the constructor and destructor are called.

#include <iostream>

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

private:
    int* data;
};

int main() {
    MyClass obj; // Constructor called here
    return 0; // Destructor called here
}

Here's what's happening:

  • When obj is created, the constructor runs and prints "Constructor called!".
  • When obj goes out of scope (at the end of main), the destructor runs and prints "Destructor called!".
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal