TeachMate
My ProgressJoin Session

Destructors

0/2 completed · ~0h 6m

All Topics
OOPLearnDestructors
1 / 2

Destructors

beginner
3 min read

A destructor is a special member function that runs automatically when an object is destroyed.

Purpose

  • Free resources (memory, file handles, network connections)
  • Clean up before the object is removed

Syntax

class MyClass {
public:
    ~MyClass() {
        // cleanup code
    }
};

Key Properties

  • Same name as class, preceded by ~
  • Takes no arguments
  • No return type
  • Cannot be overloaded (only one per class)
  • Called automatically when object goes out of scope

When Destructors Are Called

  1. Stack objects: When they go out of scope
  2. Heap objects: When delete is called
  3. Static objects: When the program ends
  4. Temporary objects: When the expression completes

Destructor Order

Destructors are called in reverse order of construction. Derived class destructor runs before base class destructor.

class Base {
public:
    ~Base() { cout << "Base destroyed"; }
};
class Derived : public Base {
public:
    ~Derived() { cout << "Derived destroyed"; }
};
// Derived destroyed first, then Base

Key takeaway: Destructors run in reverse construction order — derived class destructor runs before base class destructor.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects