#include<iostream>
usingnamespace std;
class name
{
public:
int* age;
name (int value)
{
cout<<"calling constructor\t"<<endl;
age = newint[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 :)
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.
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.
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!