All Courses
OOP: CONSTRUCTORS AND DESTRUCTORS

What is a Destructor?

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

Its main job is cleanup.

Basic Rules

  • The destructor name is the class name with ~ before it.
  • It has no return type.
  • It takes no parameters.
  • It cannot be overloaded.
  • It is called automatically.

Example

#include <iostream>

class Session {
public:
    Session() {
        std::cout << "Session started\n";
    }

    ~Session() {
        std::cout << "Session ended\n";
    }
};

int main() {
    {
        Session session;
    } // destructor runs here

    std::cout << "main continues\n";
}

When Does It Run?

Stack object:

{
    Session s;
} // destructor runs here

Dynamic object:

Session* s = new Session();
delete s; // destructor runs here

Smart pointer:

auto s = std::make_unique<Session>();
// destructor runs automatically when smart pointer goes out of scope

When Should You Write a Destructor?

You usually do not need to write a destructor if your class uses:

  • std::string
  • std::vector
  • std::unique_ptr
  • other RAII types

You may need a custom destructor when your class directly owns:

  • raw dynamic memory
  • file handles
  • sockets
  • operating-system resources

Manual Destructor Call?

A destructor can be called manually:

// object.~ClassName();

But normal programs should not do this. It is for advanced manual lifetime management. If the destructor runs twice for the same object, behavior can become undefined.

Viva Answer

A destructor is a special member function named with ~ClassName. It runs automatically when an object is destroyed and is used for cleanup. It has no return type, takes no parameters, and cannot be overloaded.

Quick Check

  • What is destructor syntax?
  • Can a destructor take parameters?
  • Can a destructor be overloaded?
  • When should you write a custom destructor?