In C++ please.
2.Explain the differences between shallow copy and deep copy. Explain
the kind of classes where the two copies differ. State the language
constructs that eliminate problems that this difference creates.
1) shallow copy: copying the some address part of other object is known as shallow copy. changing the one object will automatically change the other object. shallow copy simply states that the two objects will have some shared memory.
2)deep copy: copying the value in the other object address is known as deep copy. changing the one object will not effect other object.
when a class is having a pointer to any type as a member, then copying the object of that class to the other object of same class type will leads to shallow copy.
class which aren't having pointes as memeber (directly or indirectly), then copying the objects of that class type leads to deep copy.
shallow copy and deep copy ex :
struct shallow { int∗ p; // a pointer };
shallow x {new int{0}};
shallow y {x}; // ‘‘copy’’ x
∗y.p = 1; // change y; affects x
∗x.p = 2; // change x; affects y
delete y.p; // affects x and y
y.p = new int{3}; // OK: change y; does not affect x
∗x.p = 4; // oops: write to deallocated memory
Deep copy:
y.p = new int{0};
*y.p = *x.p; // changing y doesn't effect x
user defined copy constructor (member wise initialization) eliminates the problems that this difference creates
Get Answers For Free
Most questions answered within 1 hours.