Differentiate between a deep copy and a shallow copy?

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain how overloading takes place in c++?

661


How would you find out if a linked-list is a cycle or not?

642


What is #include c++?

666


What function initalizes variables in a class: a) Destructor b) Constitutor c) Constructor

784


How can you quickly find the number of elements stored in a static array?

729






Explain virtual class?

668


Can we get the value of ios format flags?

763


If you hear the cpu fan is running and the monitor power is still on, but you did not see anything show up in the monitor screen. What would you do to find out what is going wrong?

655


What is pure virtual function? Or what is abstract class?

682


Is it possible for a member function to use delete this?

655


What is a tree in c++?

637


Why c++ is so important?

695


What is the rule of three?

660


What is the size of a vector?

677


C is to C++ as 1 is to a) What the heck b) 2 c) 10

743