0

can anyone explain why the line in ~MyClass() was executed!? I don't understand when or how the object obj got deleted

3rd Apr 2018, 11:07 AM
Mohan Krishna Murthy
Mohan Krishna Murthy - avatar
5 Answers
+ 1
As Gordie said there is not answer without knowing the conditions you have. Here are some c++ samples which shows in which cases an object gets destructed. Not that in case of a function or loop the memory where it's located is still occupied by it, even if you aren't able to access it anymore. If you kill the reference to allocated memory it's called a memory leak. This should be avoided. When the programs finishes and there is still memory occupied the OS should free it. (But you shouldn't rely on that, since c++ standards actually don't care if the OS is doing the work the developer should have done.) However: here is the code. Feel free to ask when you have questions. https://code.sololearn.com/cmyMGfNUFcMc/?ref=app
3rd Apr 2018, 12:33 PM
Alex
Alex - avatar
+ 1
A1, A3 and C3 in my code's output cover your case. Theire destructors all get called when theire scope in which they were created end.
3rd Apr 2018, 12:41 PM
Alex
Alex - avatar
0
#include <iostream> using namespace std; class MyClass { public: MyClass(); ~MyClass(); }; MyClass::MyClass() { cout<<"Constructor"<<endl; } MyClass::~MyClass() { cout<<"Destructor"<<endl; } int main() { MyClass obj; }
3rd Apr 2018, 12:35 PM
Mohan Krishna Murthy
Mohan Krishna Murthy - avatar
0
I'm sorry my bad.. here is the code about which my question was👆
3rd Apr 2018, 12:36 PM
Mohan Krishna Murthy
Mohan Krishna Murthy - avatar
0
In simple words, constructor function ( in your case it is MyClass::MyClass() ) is called when an object is created (like you have created inside main()). And a destructor function ( in your case it is MyClass::~MyClass() ) is called when scope of that object becomes zero (i.e., when main() function returned 0). Hope it helps!
3rd Apr 2018, 12:46 PM
777
777 - avatar