Destructors in C++
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.
Automatic at death
Locals destruct at scope exit in reverse construction order — cleanup code runs itself, even when exceptions fly.
Release owned resources
delete[] buffer; fclose(f); unlock(m); — the destructor mirrors the constructor's acquisitions one for one.
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.
Never call directly
Explicit destructor calls belong to exotic placement-new code only; normal objects destruct exactly once, automatically.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.