0
0
CppComparisonBeginner · 4 min read

Copy Constructor vs Assignment Operator in C++: Key Differences and Usage

In C++, a copy constructor creates a new object as a copy of an existing object during initialization, while the assignment operator copies data from one existing object to another already initialized object. The copy constructor is called when a new object is declared and initialized, whereas the assignment operator is used to replace the contents of an existing object after its creation.
⚖️

Quick Comparison

This table summarizes the main differences between the copy constructor and the assignment operator in C++.

AspectCopy ConstructorAssignment Operator
PurposeCreate a new object as a copyCopy data to an existing object
When calledDuring object initializationAfter object is already created
SyntaxClassName(const ClassName &obj)ClassName& operator=(const ClassName &obj)
Default provided?Yes, by compiler if not definedYes, by compiler if not defined
Typical use casePassing or returning objects by valueAssigning one object to another
Self-assignment check needed?NoYes, to avoid errors
⚖️

Key Differences

The copy constructor is a special constructor used to create a new object as a copy of an existing object. It is called automatically when a new object is initialized from another object, such as when passing objects by value or returning objects from functions. It sets up the new object's data based on the source object.

The assignment operator is a special operator function that copies the contents from one existing object to another existing object. It is called when you assign one object to another after both have been created. Unlike the copy constructor, it must handle the possibility of self-assignment and often needs to clean up existing resources before copying.

In summary, the copy constructor creates a new object, while the assignment operator replaces the contents of an existing object. Both can be customized to manage deep copies or resource handling, but their timing and usage differ significantly.

💻

Copy Constructor Example

This example shows how a copy constructor creates a new object by copying an existing one.

cpp
class Box {
public:
    int length;
    Box(int l) : length(l) {}
    // Copy constructor
    Box(const Box &b) {
        length = b.length;
        std::cout << "Copy constructor called\n";
    }
};

int main() {
    Box box1(10);          // Normal constructor
    Box box2 = box1;       // Copy constructor called
    std::cout << "box2 length: " << box2.length << '\n';
    return 0;
}
Output
Copy constructor called box2 length: 10
↔️

Assignment Operator Equivalent

This example shows how the assignment operator copies data from one existing object to another.

cpp
class Box {
public:
    int length;
    Box(int l) : length(l) {}
    // Assignment operator
    Box& operator=(const Box &b) {
        std::cout << "Assignment operator called\n";
        if (this != &b) { // self-assignment check
            length = b.length;
        }
        return *this;
    }
};

int main() {
    Box box1(10);
    Box box2(5);
    box2 = box1;           // Assignment operator called
    std::cout << "box2 length: " << box2.length << '\n';
    return 0;
}
Output
Assignment operator called box2 length: 10
🎯

When to Use Which

Choose the copy constructor when you need to create a new object as a copy of an existing one, such as when passing objects by value or returning them from functions. It ensures the new object is properly initialized with the source object's data.

Choose the assignment operator when you want to copy data from one existing object to another existing object, for example, when updating an object after it has been created. It must handle self-assignment and resource cleanup carefully.

In short, use the copy constructor for object creation copying, and the assignment operator for copying between already created objects.

Key Takeaways

The copy constructor creates a new object by copying an existing one during initialization.
The assignment operator copies data between two existing objects after both are created.
Copy constructor is called automatically during object creation; assignment operator is called during assignment.
Assignment operator should handle self-assignment to avoid errors; copy constructor does not need this check.
Use copy constructor for initialization copying and assignment operator for replacing existing object data.