Labs ICT
Pro Login

Destructors

Destructors

A destructor is a special member function called when an object goes out of scope or is deleted. It is used to release resources like memory, file handles, or network connections.

Syntax

A destructor has the same name as the class prefixed with a tilde ~. It cannot take arguments or return a value, and there can be only one.

#include <iostream>
using namespace std;

class Resource {
private:
  int* data;

public:
  Resource(int value) {
    data = new int(value);
    cout << "Allocated\n";
  }

  ~Resource() {
    delete data;
    cout << "Freed\n";
  }

  int get() {
    return *data;
  }
};

int main() {
  Resource r(42);
  cout << "Value: " << r.get() << "\n";
  return 0;
}
Try it Yourself →