C++ Destructors

🧹 C++ Destructors – Clean Up Before You Leave

In C++, a destructor is like turning off the lights when you leave a room. It’s a special function that runs automatically when an object is about to be destroyed. 🕯️

💭 Why Use a Destructor?

  • It helps release memory or clean up things
  • It runs automatically when the object dies
  • Useful for files, dynamic memory, or goodbye messages 😄

🔧 Example: Destructor in Action

#include <iostream>
using namespace std;

class Box {
public:
    Box() {
        cout << "Constructor: Box created!" << endl;
    }

    ~Box() {
        cout << "Destructor: Box destroyed!" << endl;
    }
};

int main() {
    Box b1;
    {
        Box b2;
    } // b2 goes out of scope here

    cout << "End of program!" << endl;
    return 0;
}

Try It Now

📌 Rules of Destructors

  • Starts with ~ and has the same name as the class
  • It takes no parameters
  • You can’t overload it (only one destructor per class)
  • Called automatically when object goes out of scope or is deleted

🔄 Constructor vs Destructor

  • Constructor – Sets things up when object is created
  • Destructor – Cleans up when object is destroyed

🧠 Summary

  • Destructors run automatically when objects die
  • They help clean up resources (like memory or files)
  • Use them to be a responsible programmer! 🧼

Now your C++ objects know how to say both “Hello” and “Goodbye!” 🎉