0

I am trying to understand pointers in C++. The m4.set(1,1) is changing both the m3 and m4 variables. However, when I am calling the m4.set(1,1) I only want to change m4 and not m3. Can anyone help me out in this regard. Thank you. Here's a code snippet:

#include <iostream>
using namespace std;
class C {
private:
  int* d;
  int sz;
public:
  C(int* vals, int size)
    :d(new int[size]), sz(size) {
    for (int i = 0; i < size; i++)
        d[i] = vals[i];
  }
  ~C() = default;
  C(const C& other) = default;
  C& operator=(const C& other) = default;
  int get(int i) const { return d[i]; }
  void set(int i, int x) const { d[i] = x; }
  int length() const { return sz; }
};
void display(C m) {
  cout << "[ ";
  for (int i = 0; i < m.length(); i++)
    cout << m.get(i) << " ";
  cout << "]" << endl;
}
int main() {
  int b[] = { 13,63,45 };
  C m3(b, 3);
  C* mp = new C(m3);
  cout << "m3: ";  display(m3); 
  cout << "*mp: ";  display(*mp);
  C m4 = m3;
  m4.set(1, 1); // this should not change m3's array of int!!
  cout << "m3: ";  display(m3); 
  cout << "m4: ";  display(m4); 
  return 0;
}
Gohar
  • 1
  • 3
  • The defaulted copy constructor and assignment operator perform a memberwise copy. This means that, after `C m4 = m3;`, you end up with `m4.d == m3.d` - both instances hold a pointer to the same data. – Igor Tandetnik Nov 26 '20 at 04:03
  • @OP -- At the duplicate link, please read the **Managing resources** section, as your issue matches exactly with what that section describes. Long story short -- your `C` class has incorrect copy semantics -- you need to implement the requisite functions, and not `default` them. – PaulMcKenzie Nov 26 '20 at 04:19

1 Answers1

1

You should implement the copy constructor and assignment operation to deep copy the array.

Yang Jian
  • 11
  • 1