-1
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
Paddyd
  • 1,870
  • 16
  • 26
Poorvi
  • 125
  • 8

3 Answers3

0

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • >My intension was to display that any change in the value of p because of s1 will reflect the value of p in s2 also.Could you pls make a bit change in the above program to get the output like that. – Poorvi Aug 21 '13 at 12:55
0

My approach was right,just make the variable p as public and print *(s2.p) right after calling s1.disp();.I can see the value of p for s2 displaying as 200

Poorvi
  • 125
  • 8
0

In your code, you modify p in the method dist :

*p = x;

In the second case, when you call s2.disp() the default value 0 is used, and *p has the value 0.

To reflect what you want, you can do :

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

    void Display() const    // Display method just display
    {
        cout << "Value at p :" << *p << endl << p << endl;
    }

    void UpdateP( int x = 0 )
    {
        *p = x;
    }
};

s s1;
s s2 = s1;    
s1.UpdateP(200);
s1.Display();
s2.Display();

Just a live example, the code is not the prettiest but it shows you that it is working.

Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62