Thursday, July 9, 2009

What is the difference between the Assignment Operator ( = ) and Copy Constructor in C++ language?

What is the need to use copy constructor when assignment operator is doing same function?

What is the difference between the Assignment Operator ( = ) and Copy Constructor in C++ language?
Assignment operator and copy constructors are not the same.





Copy constructor is of major use when you handle pointers.





Consider you have a class c1 which has a pointer p1. Consider you have created an object o1 for this class c1 with the pointer p1 pointing to a memory location m1.





If you use assignment operator and create another object say, c1 o2 = 01; then the pointer p1 in o2 also will be pointing to the same memory location m1. If you make any changes to the memory location m1 through o1, it will be affected in object o2 also. This type of copying objects is known as shallow copy where the pointers are copied instead of the values to which they point ti.





If you use copy constructor, you can manually copy all values. So, if you want to create an object o2 similar to object o1, in the copy constructor, you create a new memory location m2 and make the pointer p1 of object o2 to point to m2. Both m1 and m2 will point to different locations but the locations to which they oint have same values. So, if you change value in one object, it will not be changed in the other object. This type of copy is known as deep copy.


No comments:

Post a Comment