The copy constructor and assignment operator are both used to copy data from one object to another, but they are invoked in different situations. Understanding the difference between them is important for correctly managing object creation and assignment in C++.
- A copy constructor is called when a new object is created using an existing object.
- An assignment operator is called when an already existing object is assigned the value of another existing object.
Example: The following program demonstrates the difference between a copy constructor and an assignment operator.
#include <iostream>
using namespace std;
class Test {
public:
Test() {}
Test(const Test&) {
cout << "Copy constructor called" << endl;
}
Test& operator=(const Test&) {
cout << "Assignment operator called" << endl;
return *this;
}
};
int main()
{
Test t1, t2;
t2 = t1; // Assignment operator
Test t3 = t1; // Copy constructor
return 0;
}
Output
Assignment operator called Copy constructor called
Explanation: t2 = t1; assigns one existing object to another, so the assignment operator is called. Test t3 = t1; creates a new object using an existing object, so the copy constructor is invoked.
Copy Constructor
A copy constructor is a special constructor that creates a new object as a copy of an existing object.
- Called when a new object is initialized from an existing object.
- Creates a separate object with its own memory.
- Automatically generated by the compiler if not explicitly defined.
Syntax
ClassName(const ClassName& obj);
Assignment Operator
The assignment operator copies the contents of one existing object into another existing object.
- Invoked after both objects have already been created.
- Copies the data from the right-hand object to the left-hand object.
- Compiler provides a default assignment operator if one is not overloaded.
Syntax
obj2 = obj1;
or
obj2.operator=(obj1);
Copy Constructor vs Assignment Operator
| Feature | Copy Constructor | Assignment Operator |
|---|---|---|
| Purpose | Creates a new object as a copy of an existing object | Copies the contents of one existing object to another existing object |
| Called When | A new object is initialized using an existing object | An existing object is assigned the value of another existing object |
| Memory | Creates a separate object with its own memory | Does not create a new object; copies data into an existing object |
| Function Type | Special constructor | Overloaded assignment operator (operator=) |
| Compiler Support | Compiler provides a default copy constructor if one is not defined | Compiler provides a default assignment operator if one is not overloaded |
| Syntax | ClassName(const ClassName& obj) | obj2 = obj1; |
| Example | Test t2 = t1; | t2 = t1; |
| Typical Use | Object creation | Object assignment |
Related article: When is a Copy Constructor Called in C++?