+ 5
What is the purpose of destructors ?
Destructors are method like constructors which destroys the objects and free up memory bla bla..... Here I am attaching a code from lesson on CPP and in this code it is clear that when we instantiate a object it's constructor function and and destructor function get executed. and object get destroyed as soon as it is created. We can't access it's attributes because object will no longer exist. Why would we need that object in the first place, Because it's getting destroyed when we create it, we can't use its attributes we can't use that objects itself. That raise the question why we need destructors? https://code.sololearn.com/cLoH6BpgkPqx/?ref=app
3 Réponses
+ 2
In short, when you call a constructor, memory space is reserved and initiated with some values; when you call a destructor, memory space is released and initialised back to nothing (null/void). You rent a house, decorate it as you want, put everything back at place while leaving.
+ 3
I think that class was designed solely for the purpose of showing what happens when an object is instantiated (constructor is invoked), and destroyed (destructor is invoked), nothing more.
The main procedure only contains an instruction for instantiation of the class, it returns immediately, nothing follows that line, that's why the destructor is invoked immediately after constructor, because main procedure is about to exit, anything within the main procedure will be discarded/destroyed.
0
My original C/C++ utf16 codes used the constructor/destructor pattern:
https://code.sololearn.com/c4kj6KYs6GnW/?ref=app
The destructor exists because I make a persistent terminal change in the constructor. SoloLearn's output is a don't-care item, but if you tried it at home and removed the destructor, my prog would permanently change the environment (here, character encoding) simply by being executed.
No big deal, but what if:
* a parent spawns my process as a child
* my code gets included as a library function
* I switch the terminal type or go to graphics mode
In this example, failing to restore initial state is a little like letting someone stay overnight, only to find out tomorrow that they've redecorated with the contents of the garbage can, rearranged the furniture and then left.