Differentiate between a deep copy and a shallow copy?



Differentiate between a deep copy and a shallow copy?..

Answer / ritesh pal

Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.

Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.

Explanation:

Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.

If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C++ General Interview Questions

What is time_t c++?

0 Answers  


What is a pdb file?

0 Answers  


What are the stages in the development cycle?

0 Answers  


What is the default access level?

0 Answers  


Write a program to get the value of sin (x) using a library function , when x is given in degrees.

1 Answers  






How can you find the nodes with repetetive data in a linked list?

1 Answers   Lucent,


Who was the creator of c++?

0 Answers  


What are Binay tress and B trees? Diff between them?

8 Answers   CTS, GATE, Wipro,


How do I run a program in notepad ++?

0 Answers  


What is the use of lambda in c++?

0 Answers  


what is data Abstraction

2 Answers  


Explain the isa and hasa class relationships. How would you implement each?

0 Answers  


Categories