Sunday, December 30, 2012

copy constructor in c++ deep copy shallow copy...


Copy Constructor

·           A special kind of constructor in C++
·           Creates a new object as a copy of an existing one
·           There exists an implicit copy constructor in all classes in C++ that do not define one
·         Unfortunately, it only creates a shallow copy of all the data members
·       This will create problems when a class has data that involves pointers to dynamic memory

Deep copy and shallow copy ::
·           Shallow copy – used to copy direct values
·         If you make a shallow copy of a pointer, you would have two pointers that point to the same location
·           Deep copy – used to copy indirect values
·         If you make a deep copy of a pointer, you will have two pointers that point to different locations but those locations have the same value
·           Modifying the original object should not affect its copy or vice versa

·           Explicit Use:
·         Building a(4);     // standard constructor call
·         Building b(a);     // b is now a deep copy of a
·           Implicit Use #1:
·         Building a(4);     // standard constructor call
·         Building b = a;    // implicit call to the copy constructor
·           Implicit Use #2:
·         When an object is returned by value from a function

·           Common Misunderstanding:
·         Building a(4);     // standard constructor call
·         Building b(3);     // standard constructor call
·         b = a;                          // does NOT call copy constructor
·           The copy constructor is never called in this code
·           The last line uses the assignment operator which may be overloaded in C++




Destructor
l For an object created on the stack:
-     the destructor is automatically invoked when the object goes out of scope
l For an object that was dynamically allocated on the heap:
-     the destructor called when the “delete” command is used on the object

No comments:

Post a Comment

Creating mirror of BST