Learn C++
#include "oopbasics/destructors.hpp"

Destructors in C++

//concept

The destructor (~ClassName(), no parameters, no return) runs automatically when an object dies — end of scope for locals, delete for heap objects — releasing whatever the object owns. This deterministic cleanup is the engine of RAII: files close, locks unlock, and memory frees themselves exactly when their guard object expires.

One destructor per class, never overloaded, never called explicitly in normal code. Any class owning resources (or designed as a polymorphic base) needs a considered destructor — virtual for bases, so deleting through a base pointer runs the whole destruction chain.

//how it works
1

Automatic at death

Locals destruct at scope exit in reverse construction order — cleanup code runs itself, even when exceptions fly.

2

Release owned resources

delete[] buffer; fclose(f); unlock(m); — the destructor mirrors the constructor's acquisitions one for one.

3

Virtual for base classes

Deleting a derived object through a base pointer with a non-virtual destructor skips derived cleanup — undefined behavior from one missing keyword.

4

Never call directly

Explicit destructor calls belong to exotic placement-new code only; normal objects destruct exactly once, automatically.

//example
#include <iostream>
 
class Tracer {
public:
Tracer() { std::cout << "born" << std::endl; }
~Tracer() { std::cout << "gone" << std::endl; }
};
 
int main() {
{
Tracer t;
}
std::cout << "after" << std::endl;
return 0;
}
Output
born
gone
after
1Entering the inner block constructs t, printing born.
2Leaving the block destroys t before anything else runs, printing gone — deterministic, no garbage collector involved.
3after prints last, proving destruction happened at scope exit, not program end.
//use cases
Closing files, sockets, and handles automatically at scope exit
Releasing heap memory owned by legacy classes without manual delete calls
Unlocking mutexes via lock_guard so exceptions can't leave them held
Marking base-class destructors virtual to keep polymorphic deletion safe

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.