Day1 of #daily_code
Learnt Shallow Copy and Deep Copy concept in C++
------------------------------------------------
Generally if we want to copy one object to other then we create exact one replication of that object including all attributes. So there is two ways to copy.
?1. Shallow Copy 2. Deep Copy
When we simply copy one object to the other then it is called (Shallow Copy). This works only if the attributes are not defined in Heap segment of memory means the memory segment where Dynamic Memory Allocation takes place. So if there is something like pointers or array in our class then Deep copy is preferred over shallow copy.
Lets discuss about shallow copy....I have mentioned a program to demonstrate what Shallow copying is.
hi program outputs to followingThis program outputs to followingThis program outputs to followiThe above program outputs to :
When the attributes are like pointers and arrays and if we perform shallow copy for copying one object to the other then it creates ambiguity between two objects as both will point to the same memory location allocated dynamically.
Changing the value of one will also change the other. But we know attributes are similar for all objects but their state differs. State of an object means the value in object attributes. So to avoid this we use Deep Copy. It is done by explicitly creating a copy constructor and the attributes which use dynamic memory allocation is initialized twice so as to specify that a particular memory belongs to a particular object. It will be more clear after understanding the program that I have specified below.
Thank you ! Please Support.....