When is the destructor "called"? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

When is the destructor "called"?

Dunno if "called" is the right term but when is an object destroyed and the destructor called?

5th May 2017, 10:55 AM
Vodolle
Vodolle - avatar
7 Answers
+ 1
When you delete the object via pointer, when the actual object leaves scope (at the end of the block {}) or when you call the destructor explicitly.
5th May 2017, 11:22 AM
Denis Felipe
Denis Felipe - avatar
+ 2
This answers are still somewhat unclear for me but I guess I'll find out after some practice and research but thank you alot for commiting to help me
5th May 2017, 11:14 AM
Vodolle
Vodolle - avatar
+ 1
When the object is removed from memory as it's no longer needed destructor is called.
5th May 2017, 11:02 AM
Nantha
Nantha - avatar
+ 1
Do you mean when I use delete obj; the destructor is called? Or for when the object is used the last time in a programm?
5th May 2017, 11:05 AM
Vodolle
Vodolle - avatar
+ 1
As soon the object lose its scope that is life time of variable is finished.
5th May 2017, 11:10 AM
Nantha
Nantha - avatar
+ 1
I found an answer on stackoverflow about this "out of scope" thing and understood it finally Thanks for the answers, I just wasn't understanding this scope stuff but now I got it
5th May 2017, 5:53 PM
Vodolle
Vodolle - avatar
0
If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope. If the object was created with a new expression, then its destructor is called when the delete operator is applied to a pointer to the object.
7th May 2017, 5:40 AM
Erick Nyagilo
Erick Nyagilo - avatar