Thursday, July 9, 2009

What is the need of copy constructors & assignment operator overloading in C++?

copy constructors are cloning an abject. assignmet operator is there to enable saying a = b for objects, especially those with pointer members. if you don't define them, the compiler will define them for you, but very dangerous to use compiler defined ones if your object has pointers. Because then you would have two objects sharing member data. if you delete this data using this, and rfer to it through the other object, your code crashes.. hope this helps

What is the need of copy constructors %26amp; assignment operator overloading in C++?
C++ supports 'poly-morphism'. This means that functions and operators can perform more than one task depending on the type of data. When a function or an operator exists in mopre than one form, it is said to be overloaded. Suppose you have declared a class complex which represents complex objects, then performing a taks like assigning one complex object to another would need code like assign(comp1, comp2); however, overloading allows you to write code like comp2 = comp1 by overloading operator =. Note that is no longer an opertor. It is now a function and will perform the task as defined by you. So if you write code that will add the two complex objects in the definition for =, comp2 = comp1 will result in addition instead of assignment.
Reply:These are needed to change the default behavior of what happens when an instance is copied to another instance. By default, each member of the class or struct are copied one by one from one instance to another. For instance, assume you have two instances of class Person called p1 and p2. The class has two fiels, FirstName and LastName. When you say:


p1 = p2;


then the FirstName and LastName fields from p2 are copied to p1.


That's the default behavior.





Now, if you want to change that default behavior, then you specify a custom copy constructor and an assignment operator for the class Person to do something other than member-wise copy.





You need *both* the copy constructor and assignment operator.


The copy constructor is invoked when the copy is made at the time that the new instance is constructed, as in:





Person p2 = p1;





The assignment operator is invoked if the copy is done after p2 is already constructed, as in:





p2 = p1;





Hope this helps.

gladiolus

No comments:

Post a Comment