Saturday, April 15, 2017

Need for copy constructor...

The following examples try to bring out the need for having a copy constructor. With out a copy constructor if we allocate on object to other, i.e. object1=object2, the compiler internally does a bitwise copy,which works fine as long as there are no pointers present in the member variables of the object. A bit wise copy ends up copying the pointer too as it is, making pointers of both the objects point ot the same memory location.

This is depicted in the example below.



Output :



We can clearly see in the output above that the bar1 variable in both the objects is pointing to the same memory location so even when we modify only the variable in one object, the change is reflected in other object too which should no be the case as the two subjects are not related to each other.

The following example illustrates the same with the use of copy constructor.



Output:



In the above output it is clearly visible that the two objects have bar1 pointing to different memory location and changing the value in one object does not affect the other.

No comments:

Post a Comment