0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Arif Hamim
  • 57
  • 1
  • 11
  • I would expect 5 executions of the destructor. You have 2 objects and 3 temporaries. – drescherjm Mar 01 '18 at 18:34
  • Your "neg(dyna ob)" function is pass by value so it creates a copy of your object. Try "neg(const dyna &ob)" to pass by reference. – Marker Mar 01 '18 at 18:36
  • Passing by value will create a temporary objects thus a constructor/destructor are invoked. – Raindrop7 Mar 01 '18 at 18:37

1 Answers1

1

Because you do not pass dyna ob into neg by reference or address, a dyna with scope local to the function is created and destroyed each time you call it. This produces the first 3 Freeings you see printed out. The last 2 are when o and o2 are destroyed in main.