Why do we need Constructors and Destructors? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why do we need Constructors and Destructors?

I am doing the lessons on classes I dont know why I need to know them in code? Maybe give an example where you need to use them in code

12th Jun 2017, 12:33 AM
koala 🐨
koala 🐨 - avatar
2 Answers
+ 8
A constructor does some kind of task every time an object is made. It might give some default values to the variables, or write to a log file, or some other needed task. Destructors do something once an object is disposed of to free memory. If the object uses a database or file, it can disconnect from it, which saves more memory. For where you probably are right now, you might want it to try experimenting with them, but it might not be​ necessary for anything you could write.
12th Jun 2017, 1:33 AM
Tamra
Tamra - avatar
0
damn almost 2 years later, i never chose best answer woops and i understand this perfectly:)
4th Apr 2019, 10:54 PM
koala 🐨
koala 🐨 - avatar