0

what is the use of constructor and destructors in a class ?

Even if we dont use destructors and constructors ,how will it effect the code ? what is gthe benefit of using constructors and destructors?please explain both briefly

8th Jun 2017, 5:45 AM
Rishabh Joshi
Rishabh Joshi - avatar
4 Réponses
+ 3
Even if you dont define your own the compiler will still create them as defaults. Constructor is for doing the stuff you put in it when the object is first created. Destructor does the opposite, it gets called when the object is deleted or it goes out of scope. It will also execute the code you put in it.
8th Jun 2017, 5:42 AM
aklex
aklex - avatar
+ 3
To deallocate the whole class and any resources it is using. You normally define your own if you need to execute some code that cleans up stuff, like deleting dynamic arrays that you allocated
8th Jun 2017, 5:48 AM
aklex
aklex - avatar
+ 1
Constructor runs when an object is created whereas runs when an when it was deleted.
12th Jun 2017, 11:57 AM
vardhan_11
0
i am confused about destructors. If my object goes out of scope ,whats the role of destructor even if i dont declare it
8th Jun 2017, 5:44 AM
Rishabh Joshi
Rishabh Joshi - avatar