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;
}