Search code examples
c++pointersclass-constructors

C++ - Copy constructor with pointers as the data field


I have the following code :-

#include <iostream>
using namespace std;

class A { 
    int *val;
public:
    A() { val = new int; *val = 0; }
    int get() { return ++(*val); } 
};

int main() {
    A a,b = a;

    A c,d = c;

    cout << a.get() << b.get() ;
    cout << endl ; 

    cout << c.get() << endl ;//
    cout << d.get() << endl;
    return 0;
}

It produces the output as :-

21
1
2

The behavior in case of c.get and d.get is easy to understand. Both c and d share the same pointer val and a and b share the same pointer val.

So c.get() should return 1 and d.get() should return 2. But I was expecting similar behavior in a.get() and b.get(). (maybe I have not understood cout properly)

I am unable to understand how a.get() is producing 2.

Can you explain why I am getting such an output. According to me the output should have been :-

12
1
2

Solution

  • cout << a.get() << b.get() ;
    

    gets executed as:

    cout.operator<<(a.get()).operator<<(b.get());
    

    In this expression, whether a.get() gets called first or b.get() gets called first is not specified by the language. It is platform dependent.

    You can separate them into two statements to make sure they get executed in an expected order.

    cout << a.get();
    cout << b.get();