what is the main purpose of a destructor?
could you give any examples of what i might want to run when a object is deleted?
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
Constructor is involved automatically when the object is created. Destructor is involved automatically when the object is destroyed. Used to initialize the instance of a class. Used to de-initialize objects already existing to free up memory for new accommodation.
Advantages of Destructor in C++It gives a final chance to clean up the resources that are not in use to release the memory occupied by unused objects like deleting dynamic objects, closing of the system handles, used files.
Destructor function is called automatically when the object goes out of scope. When a class contains dynamic object then it is mandatory to write a destructor function to release memory before the class instance is destroyed this must be done to avoid memory leak.
It gives the object an opportunity to prepare to be killed. This could mean manual cleanup, state persistence, etc.
For example, a Model may want to save all of its current properties back into the database.
Or, a Database object itself might want to close the socket it is using to communicate to a database server.
So, you probably know what a constructor does. If a constructor sets up, a destructor cleans up. Here's an example from the PHP site:
<?php class my_class { public $error_reporting = false; function __construct($error_reporting = false) { $this->error_reporting = $error_reporting; } function __destruct() { if($this->error_reporting === true) $this->show_report(); unset($this->error_reporting); } ?>
Here's the link to the PHP documentation on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With