I'm starting to learn class in c++ , so the idea destructor is being a bit confusing to me . Here's a sample code that I tried to understand how destructor is called.
#include<bits/stdc++.h>
using namespace std;
class dyna
{
int *p;
public:
dyna(int i);
~dyna() { delete(p); cout<<"Freeing"<<endl; }
int get()
{
return *p;
}
};
dyna::dyna(int i)
{
p = new int;
*p = i;
}
int neg(dyna ob)
{
return -ob.get();
}
int main()
{
dyna o(-10);
cout<<o.get()<<endl;
cout<<neg(o)<<endl;
dyna o2(20);
cout<<o2.get()<<endl;
cout<<neg(o2)<<endl;
cout<<o.get()<<endl;
cout<<neg(o)<<endl;
return 0;
}
OUTPUT:
-10
10
Freeing
20
-20
Freeing
20
-20
Freeing
Freeing
Freeing
My question is that why it's showing last 3 "Freeing"? I understand first of them for being out of scope of int neg(dyna ob)
. But why the last two one ? Please help.