Search code examples
c++copy-constructordeep-copy

Why the value of same variable in heap of object 1 not reflected in object2?


s(const s& src)
{ 
    cout<<"Copy\n";
    p =src.p;
}

void disp(int x=0)
{  
    *p = x;
    cout <<"Value at p :"<<*p <<endl<< p<<endl;
}

};// relevant piece of code


s s1;
s s2 = s1;    
s1.disp(200);
s2.disp();

In this program what i was expecting was since the data member p of objects s1 and s2 point to the same memory location any change in the value of p of object s1 should reflect the value of p in object s2.In the output its clear that address holded by p is same for both s1 and s2.but i didnt get the expected result 200 for s2.disp function.Output is

Copy
Value at p :200
0x1e069010
Value at p :0
0x1e069010

Solution

  • You modify p in disp - *p = x;. When you call s2.disp(); the default 0 is used. (void disp(int x=0)), so you set *p to 0.