Constructors and destructors get me confused! Help? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
+ 2

Constructors and destructors get me confused! Help?

Ok so far I understand constructors create objects and destructors destroy objects... But I can't comprehend what it ACTUALLY means. How can objects be created? Do we need to create the class first? Why is it used? And why do we destroy them?

10th Oct 2018, 1:13 AM
Kenneth De Coster
Kenneth De Coster - avatar
4 Respostas
+ 5
Every object you create needs to live somewhere in memory. The way this works is that C++ asks your operating system for memory, the OS responds with something like "sure here's one megabyte", and then C++ will place all the objects you create in the memory it just got. This also means that you want to destroy objects you no longer need to free up space. If you never destroy objects and just use more and more memory that's called a "memory leak" and it can freeze or crash your computer in the worst case! Constructors/destructors don't create or destroy objects, but rather they are called right after creation/right before deletion. The memory you get from the operating system usually contains whatever the last program running wrote there, in other words garbage. So you better set all the variables of your objects to good default values in the constructor. The destructor is for cleanup. Maybe you've created some files that you won't need after the object is gone so you delete them in the destructor.
10th Oct 2018, 2:49 AM
Schindlabua - avatar
+ 2
Simply sorted, constructor is used to create the objects using respective class name and to allocate memory. instead of destructor we use finalize method in java since java is a garbage collected language.
10th Oct 2018, 3:16 AM
Nishanth - avatar
+ 2
It is an inherited method.
10th Oct 2018, 3:17 AM
Nishanth - avatar
+ 2
Constructors A single class can have multiple constructors with different numbers of parameters.
23rd Oct 2018, 12:44 PM
Wendafrash Buzuayew
Wendafrash Buzuayew - avatar