+ 2

C++ Destructors

Hey, How come should I make destructors for my classes? and what should I write in the destructors? ~MyClass() { // what to write? }

17th Aug 2021, 10:56 AM
Yahel
Yahel - avatar
5 Réponses
+ 3
Yahel, It's just how I see it. Keep the door open for expert opinions 👍
17th Aug 2021, 11:21 AM
Ipang
+ 1
Ipang, so assume i only have a std::string and an int in my class; should I not have a destructor? and if i have a Heap allocated array (new int[]); should I type: delete[] arr; in the destructor? is that it?
17th Aug 2021, 11:05 AM
Yahel
Yahel - avatar
+ 1
I think std::string is implemented with its own logic for clean-up chores. Yes if the int[] is defined with `new`
17th Aug 2021, 11:09 AM
Ipang
+ 1
Ipang, Thanks :) Summary: If the class contains Heap Allocated members - Make sure to delete them in the Destructor. Stack Allocated members will get deleted by themselves when they are out of scope...
17th Aug 2021, 11:16 AM
Yahel
Yahel - avatar
0
Use a destructor when your class contains dynamically allocated data, you can deallocate the memory that was used for the data inside the destructor.
17th Aug 2021, 11:01 AM
Ipang