+ 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? }
5 Respostas
+ 3
Yahel,
It's just how I see it. Keep the door open for expert opinions 👍
+ 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?
+ 1
I think std::string is implemented with its own logic for clean-up chores.
Yes if the int[] is defined with `new`
+ 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...
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.