educative.io

C++ : data members that cannot be shallow copied

Hi.
What does mean shallow copy?
Way data members like pointers or resource ids cannot be shallow copied?
Thanks!

Hi @Sergio_Acosta , can you please share the lesson link? Thanks!

Copy and Move Constructors

Thanks!!

Hello @Sergio_Acosta

A shallow copy is a copy of an object’s data members where the values of the data members are simply copied over from the original object to the copy. In other words, the copy points to the same memory location as the original object’s data members.

Data members like pointers or resource ids cannot be shallow copied because they represent external resources that are not a part of the object itself. If you simply copy the value of a pointer or resource id from the original object to the copy, then both objects will be pointing to the same resource, and any modifications made to the resource through one object will affect the other object as well. This can lead to unexpected behavior and bugs in the program.

To avoid this, you need to perform a deep copy of the object’s data members, where new memory is allocated for the copied data members and their values are copied over. This ensures that the copy and the original object have their own separate resources and can be modified independently. This is why a copy constructor might be necessary for classes that have data members that cannot be shallow copied.

I hope this will help
Happy Learning

1 Like

It is clear when you say “external resources” for pointers or resource ids,
but if in the case of a shallow copy “the copy points to the same memory location as the original object’s data members”, then don’t we have the same undesired interaction between both objects?. For a shallow copy, new memory allocation is not needed, is it?

Thanks! @Muhammad_Ali_Shahid

Hello @Sergio_Acosta

You are correct. In the case of a shallow copy, both the original object and the copy will be pointing to the same memory location for the data members that are being shallow copied. It can lead to undesired interactions between both objects if they modify the shared resource.

As you mentioned, in the case of a shallow copy, new memory allocation is unnecessary because the copy points to the same memory location as the original object’s data members. It can be helpful when you want to share resources between objects or avoid the overhead of allocating new memory. However, in cases where you want independent copies of the data members, a deep copy is necessary.

I hope this will help
Happy Learning

1 Like