Query in implicit assignment operator

Hi,
I am trying following program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
using namespace std;

class name
{

public:
int* age;

 name (int value)
{
  cout<<"calling constructor\t"<<endl;

   age = new int[value];
}

~name()
{
  cout<<"calling destructor\t"<<endl;
  delete [] age;
}
};

int main()
{

 name n1(10);
 //name n2(20);
 {
  n1.age[0]=100;
  cout<<n1.age[0]<<endl;
  cout<<"address of n1 is \t"<<n1.age<<endl;

 name n2(20);
  n2.age[0]=200;
  cout<<"address of n2 is\t"<<n2.age<<endl;

  cout<<endl;

  n2=n1;

  cout<<"address of n1 is\t"<<n1.age<<endl;
  cout<<"address of n2 is\t"<<n2.age<<endl;
 }
//n1.age[0] = 200;
//cout<<n1.age[0]<<endl;

return 0;



calling constructor
calling constructor
100
address of n1 is        0x9a02f0
address of n2 is        0x9a0320

address of n1 is        0x9a02f0
address of n2 is        0x9a02f0
calling destructor
calling destructor
Aborted (core dumped)


At line 43, n2 goes out of scope. So ideally, destructor should get called for n2, that is, only once. But I see desctructor is called twice!. Not sure why.

Could somebody please explain? Thanks in advance :)
Last edited on
n1 and n2 both go out of scope on line 47. Everything is alright.

Well not everything. I think you're leaking memory (n2.age is not freed).
Last edited on
Modified the program. Still the same result. Agreed, both go out of scope at line 47..But shouldn't n2 go out of scope at line 44? That means destructor will get called twice for n2 and once of n1(at line 47), that is, total 3 times. But I still see destructor gets called only twice.
Now n2's destructor is called at line 44 and n1's destructor is called at line 48.
Everything is fine(except for the memory leak).
As Caligulaminus has said a couple of time, there is a memory leak. But the cause of your core dump is the related problem of you deleting the same memory twice.

Because you did not define an assignment operator for class name, when you assign n2 to n1 (line 40), the default assignment operator is called, and all of the fields from n1 are copied into n2. That means that n2's old value of age is lost, and it now points to the array allocated by n1.

So now, the 20-int array is leaked, and both n1 and n2 try to delete the 10-int array.

Edit: fixed typo
Last edited on
Argh!
Double delete - how could I miss that. m(
Thanks guys :). I deliberately did not define overloaded assignment operator because I wanted to see the effects of memory leaks :). Got the concept now ;)
Cheers!
Topic archived. No new replies allowed.