Difference between a "assignment operator" and a "copy constructor"

Questions by suji   answers by suji

Showing Answers 1 - 5 of 5 Answers

Lily

  • Sep 28th, 2005
 

Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function's return value, a temporary copy of that object is made.

Assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal.

Doreen

  • Jun 14th, 2006
 

If a class contains members that are pointers initialized by new, then you should define a copy constructor that copies the pointed-to data instead of copying the pointers themselves. This is termed deep copying. The alternative form of copying (memberwise, or shallow, copying) just copies pointer values. A shallow copy is just that?the shallow "scraping off" of pointer information for copying, rather than the deeper "mining" required to copy the constructs referred to by the pointers.

The overloaded assignment operator is used when you assign one object to another existing object:

 

The solution for the problems created by an inappropriate default assignment operator is to provide your own assignment operator definition, one that makes a deep copy. The implementation is similar to that of the copy constructor, but there are some differences.

1.   Because the target object may already refer to previously allocated data, the function should use delete[] to free former obligations.

2.   The function should protect against assigning an object to itself; otherwise, the freeing of memory described previously could erase the object's contents before they are reassigned.

3.   The function returns a reference to the invoking object.

 

Indrajit Paul

  • Jul 13th, 2007
 

Inspite of repeated requests by some (few) sensible people to everybody to read the question properly before responding, nobody listens.

For doreen, the question does not ask you to explain deep copy and shallow copy mechanism neither does is asks how assignment operator should be written.

It asks the difference between a assignment operator and a copy constructor.

The difference is, a assignment operator (default or user provided) is called when the object already has been instantiated. A copy constructor is called when the object has not yet been constructed.

For Example.

Class A{/*...*/};

main()
{
   A a;
   A b = a; /* copy constructor will be called */
   A c;
   c = a; /* assignment operator will be called*/
}

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions