To be honest, I have the feeling the actual problem is that you do not fully understand the difference between a shallow copy and deep copy in c++.
In very simple terms: shallow copy = copy the pointer, deep copy = copy what the pointer points to.
Your code is a variation of deep copy by taking what the pointer points to and create a new instance from that (assuming it would compile).
I will give you a simple example and leave the rest to you:
#include <iostream>
struct foo {
int * some_pointer;
void deep_copy( const foo& other) {
// copy the value
*some_pointer = *(other.some_pointer);
}
void shallow_copy( const foo& other) {
// make some_pointer point to the same as other.some_pointer
some_pointer = other.some_pointer;
}
};
int main() {
int x = 0;
int y = 42;
foo f{&x};
foo g{&y};
f.deep_copy(g);
y = 3;
std::cout << *f.some_pointer << "\n";
std::cout << *g.some_pointer << "\n";
f.shallow_copy(g);
y = 5;
std::cout << *f.some_pointer << "\n";
std::cout << *g.some_pointer << "\n";
}
This prints:
42
3
5
5
Because first f.deep_copy(g);
copies the value and afterwards changing the value of y
(which initially was bound to g
) has no effect on f
.
On the other hand, after f.shallow_copy(g);
both f.some_pointer
and g.some_pointer
both point to y
, hence modifiying y
is reflected on both, f
and g
.