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

Showing Answers 1 - 9 of 9 Answers

Girish

  • Jul 23rd, 2005
 

assignment operator -> which are performed of basic data types like int , float ,char ,long etc . 
but copy constructor -> this can be used to assign a object of deriver data type . 
 
 
 

  Was this answer useful?  Yes

Srini

  • Sep 10th, 2005
 

Folks,Copy constructor creates / has the instance (constructor). But for = operator, the you need a instance which is created either by default constructor or normal constructor.thanksSrini

Rongkai Xu

  • Sep 14th, 2005
 

Assignment changed the value of the object that has already been constructed. But copy constructor construct a NEW object and gives it a value at the same time.

ankurgarg

  • Feb 21st, 2008
 

In C++, assignment and copy construction are different because the copy constructor initializes uninitialized memory, whereas assignment starts with an existing initialized object. If your class contains instances of other classes as data members, the copy constructor must first construct these data members before it calls operator=. The result is that these members get initialized twice. It's the same thing that happens with the default constructor when you initialize members using assignment instead of initializers.

  Was this answer useful?  Yes

a_l_soni

  • Dec 8th, 2009
 

When a Class is created there are five methods that are, by-default, created by the compiler for that class. They are:

1. Default no argument constructor.
2. Default Destructor.
3. Default Copy Constructor, without any code in it.
4. Overloaded Assignment operator.
5. Overloaded '&' operator.

Amongst these, the Copy Constructor and Assignment Operator should be implemented to handle Dynamic Memory Allocation, for the class members.

Copy Constructor -> Works for the objects that are being newly created.
 There are basically 4 scenarios in which the copy constructor  would be executed.
1. When a new object is being created using an existing object of the same class.
2. When an object is passed to a function, by value.
3. When an object is returned from a function by value.
4. When a temporary object is created.
Syntax:
MyClass (const MyClass &objMyClass)
Here the parameter is made constant to prevent accidental modifications and it is passed by reference to avoid Copy Constructor going into infinite loop.

Assignment Operator -> Works for the already existing objects.
Syntax:
MyClass& operator = (const MyClass &objMyClass)
Here the parameter is made constant to prevent accidental modifications and it is passed by reference to avoid Copy Constructor going into infinite loop. The operator returns an pointer to a MyClass object hence it returns an reference to MyClass.

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