Destructors and Cleanup
Release resources automatically.
What a Destructor Does
A destructor runs when an object's lifetime ends. Its job is to release whatever the object owns. It is named ~ClassName.
#include <iostream>
class File {
public:
~File() { std::cout << "closing file\n"; }
};
int main() {
File f;
} // ~File runs hereFreeing Owned Memory
If a class owns heap memory, its destructor must free it. This is the classic place to call delete.
#include <iostream>
class Buffer {
int* data;
public:
Buffer(int n) : data(new int[n]) {}
~Buffer() { delete[] data; } // cleanup
};
int main() { Buffer b(10); }All lessons in this course
- The RAII Principle
- Destructors and Cleanup
- Rule of Three/Five
- Scope Guards