A destructor is a special method in a [[C++]] class that is called when a value of said type is being deleted. While a [[Constructor]] are special type of [[Method]] that will run at the *beginning* of a value’s lifetime, Destructors are special [[Method]] that are executed at the *end* of an objects lifetime. >[!seealso] [[./Inheritance|Destructors in Inheritance]] Destructors are *always* implicit, you cannot call a destructor yourself. They are run when an instance of the class is being deleted, which could be from `delete` if its [[Heap]] allocated, or simply going out of scope if its stack allocated. >[!example] >```cpp > >void print_hi() { > CString string = {"What"}; > CString *heap = new CString{"bruh"}; > > delete heap; // heap.~CString is implicitly called before freeing memory >} // string.~CString is implicitly called >``` Any class can only have *one* destructor, as it is impossible to [[Overload]] a destructor when you can never call it yourself anyway. >[!warning] > A destructor is called *before* the class is freed from memory, meaning you should ***never*** do the following in a Destructor or any other [[Method]]: > >```cpp >~Foo() { > delete this; >} >``` > Doing this will result in a double free error. > Aside from that, you should never do this as this would also be incorrect if our instance of Foo was not [[Heap]] allocated, and the pointer is to a stack variable. > > In methods, if you write code like that, it *guarentees* a dangling pointer after you call that method (breaking [[The Goal]]). >```cpp >BadClass *instance = new BadClass{}; >instance.method_that_deletes_this(); >// instance is now a dangling pointer to invalid memory >``` ### Syntax The syntax for defining a destructor is a tilde (`~`) followed by the class name. >[!example] >Full Example can be found [[CString|here]] >```cpp >class CString { > // ... > ~CString() { > delete[] buffer; // delete char array > } > // ... >} >```