What's the difference between assignment operator and copy constructor in C++?

C++Server Side ProgrammingProgramming

The Copy constructor and the assignment operators are used to initialize one object to another object. The main difference between them is that the copy constructor creates a separate memory block for the new object. But the assignment operator does not make new memory space. It uses reference variable to point to the previous memory block.

Copy Constructor (Syntax)

classname (const classname &obj) {
   // body of constructor

Assignment Operator (Syntax)

classname Ob1, Ob2;
Ob2 = Ob1;

Let us see the detailed differences between Copy constructor and Assignment Operator.

Copy Constructor
Assignment Operator
The Copy constructor is basically an overloaded constructor
Assignment operator is basically an operator.
This initializes the new object with an already existing object
This assigns the value of one object to another object both of which are already exists.
Copy constructor is used when a new object is created with some existing object
This operator is used when we want to assign existing object to new object.
Both the objects uses separate memory locations.
One memory location is used but different reference variables are pointing to the same location.
If no copy constructor is defined in the class, the compiler provides one.
If the assignment operator is not overloaded then bitwise copy will be made



Updated on 30-Jul-2019 22:30:25