DEV Community

Uzair Ahmad
Uzair Ahmad

Posted on

To Copy or Not to Copy: Understanding Shallow and Deep Copying in Code

Shallow Copy:-

A shallow copy in C++ is a copy that creates a new object and copies the member variables' addresses of the original object to the new object.

However, the memory locations pointed to by the pointers in the new object are not copied, but rather their addresses are simply copied. This means that both the original object and the new object will point to the same memory locations, which can lead to unintended consequences if changes are made to the shared data.

A shallow copy can be made by simply copying the reference.

Example:-
Image description

Deep Copy:-

A deep copy in C++ is a copy that creates a new object and copies all member variables of the original object to a new object, including copying the memory pointed to by the pointers to new memory locations.

A deep copy means creating a new array and copying over the values. Changes to the array values referred to will not result in changes to the array data refers to.

Example:-

Image description

it's good programming practice to use a deep copy when you need to create a new object that is independent of the original object and does not share any data with it.

On the other hand, shallow copying is useful when you want to create a new object that shares data with the original object.

In general, if you need a new object that is independent of the original object, a deep copy is recommended, while if you need a new object that shares data with the original object, a shallow copy may be applicable.

Don't forget to follow for more amazing programming content.

Top comments (0)