+ 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?
4 Answers
+ 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.
+ 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.
+ 2
It is an inherited method.
+ 2
Constructors
A single class can have multiple constructors with different numbers of parameters.