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.


No alt text provided for this image
No alt text provided for this image

hi program outputs to followingThis program outputs to followingThis program outputs to followiThe above program outputs to :

No alt text provided for this image

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.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Thank you ! Please Support.....









要查看或添加评论,请登录

Apurba Sundar Nayak的更多文章

  • Day4 of #daily_code

    Day4 of #daily_code

    Not so much time to code today. Despite that I want a few things to be shared.

  • Day3 of #daily_code

    Day3 of #daily_code

    Learnt a bunch of things today. ----------------------------------------------------- 1.

  • Day2 of #daily_code

    Day2 of #daily_code

    Learnt a bunch of things today…

  • Discussing different formats of scanf()

    Discussing different formats of scanf()

    scanf() is basically a function declared in stdio.h and it takes input from standard input stream i.

社区洞察

其他会员也浏览了