Copy Constructor vs Assignment Operator in C++
C++ is an object-oriented programming language that has its own special features and constructs. One of the important features of C++ is the ability to manipulate objects, which includes creating objects, copying objects, and assigning objects. When it comes to copying objects, there are two ways to do it: using the copy constructor or the assignment operator. This article will cover the distinctions between the C++ "copy class" and "assignment operator."
Copy Constructor:
An existing object of the same class's values are copied into a new object by a "constructor" known as a "copy constructor," which generates new objects in this way.
The syntax for a copy constructor is as follows:
class class_name {
public:
class_name (const class_name &object) {
// Copy constructor code
}
};
The copy constructor takes an object of the same class as an argument and creates a new object with the same values. The "const" keyword indicates that the argument should not be modified.
Program:
#include<iostream>
using namespace std;
class Rectangle {
private:
int width, height;
public:
Rectangle(int w = 0, int h = 0) : width(w), height(h) {}
// Copy constructor
Rectangle(const Rectangle& other) : width(other.width), height(other.height) {
cout << "Copy constructor called." << endl;
}
int getArea() const {
return width * height;
}
};
int main() {
// Create a rectangle object
Rectangle rect1(5, 10);
// Copy the rectangle object to a new object
Rectangle rect2 = rect1;
// Print the areas of the two rectangles
cout << "Rectangle 1 area: " << rect1.getArea() << endl;
cout << "Rectangle 2 area: " << rect2.getArea() << endl;
return 0;
}
Explanation:
- This is a C++ program that demonstrates the use of a copy constructor in a class.
- The program defines a class called "Rectangle", which has two private member variables: "width" and "height", and two public methods: a constructor and a function that calculates the area of the rectangle.
- The constructor takes two integer arguments (width and height) and initializes the corresponding member variables.
- The constructor also has default arguments so that if no arguments are provided, the rectangle will be initialized with a width and height of 0.
- The class also defines a copy constructor, which takes a constant reference to another Rectangle object as its argument.
- This copy constructor is called when a new Rectangle object is created by copying an existing Rectangle object, such as in the line "Rectangle rect2 = rect1;".
- The copy constructor simply sets the width and height of the new Rectangle object to the same values as the original object.
- In the main function, a Rectangle object named "rect1" is created with a width of 5 and a height of 10. Then, a new Rectangle object named "rect2" is created by copying "rect1" using the copy constructor.
- The areas of both rectangles are then printed using the "getArea()" function of the Rectangle class.
When the program is executed, the output will be:
Copy constructor called.
Rectangle 1 area: 50
Rectangle 2 area: 50
The output shows that the copy constructor is called when the "rect2" object is created and that both rectangles have the same area of 50.
Program Output:
Assignment Operator:
An operator that is used to assign one item to another is the assignment operator.
The syntax for the assignment operator is as follows:
class class_name {
public:
class_name& operator= (const class_name &object) {
// Assignment operator code
return *this;
}
};
The assignment operator takes an object of the same class as an argument and assigns the values of that object to the object on the left-hand side of the assignment. The "&" symbol indicates that the operator returns a reference to the object. The "this" pointer is used to refer to the object on the left-hand side of the assignment.
Program:
#include <iostream>
using namespace std;
class Rectangle {
private:
int width, height;
public:
Rectangle(int w = 0, int h = 0) : width(w), height(h) {}
// Copy constructor
Rectangle(const Rectangle& other) : width(other.width), height(other.height) {
cout << "Copy constructor called." << endl;
}
// Assignment operator
Rectangle& operator=(const Rectangle& other) {
if (this != &other) {
width = other.width;
height = other.height;
cout << "Assignment operator called." << endl;
}
return *this;
}
int getArea() const {
return width * height;
}
};
int main() {
// Create two rectangle objects
Rectangle rect1(5, 10);
Rectangle rect2(2, 3);
// Use the assignment operator to copy rect1 to rect2
rect2 = rect1;
// Print the areas of the two rectangles
cout << "Rectangle 1 area: " << rect1.getArea() << endl;
cout << "Rectangle 2 area: " << rect2.getArea() << endl;
return 0;
}
Explanation:
- This is a C++ program that demonstrates the use of the assignment operator in a class.
- The program defines a class called "Rectangle", which has two private member variables: "width" and "height", and three public methods: a constructor, a copy constructor, and an assignment operator.
- The constructor takes two integer arguments (width and height) and initializes the corresponding member variables.
- The constructor also has default arguments, so that if no arguments are provided, the rectangle will be initialized with a width and height of 0.
- The class also defines a copy constructor, which takes a constant reference to another Rectangle object as its argument. This copy constructor is called when a new Rectangle object is created by copying an existing Rectangle object.
- The assignment operator is also defined in the class, and it takes a constant reference to another Rectangle object as its argument.
- The values of one Rectangle object are copied to another using the assignment operator. The operator first checks if the two objects are not the same, to avoid self-assignment. If they are not the same, it sets the width and height of the new object to the same values as the original object.
- In the main function, two Rectangle objects named "rect1" and "rect2" are created with different widths and heights. Following that, the values of "rect1" are copied to "rect2" using the assignment operator.
- The areas of both rectangles are then printed using the "getArea()" function of the Rectangle class.
When the program is executed, the output will be:
Assignment operator called.
Rectangle 1 area: 50
Rectangle 2 area: 50
The output shows that the assignment operator is called when the "rect2" object is assigned the values of "rect1". The areas of both rectangles are then printed, and they have the same value of 50.
Program Output:
Difference between Copy Constructor and Assignment Operator:
There are several significant differences between the copy constructor and the assignment operator, even though both are used to copy objects.
Purpose: The copy constructor is used to create a new object and initialize it with the values of an existing object. On the other hand, the assignment operator is used to assign one object to another, which means that it updates the values of an existing object with the values of another object.
Syntax: There are differences between the syntax of the assignment operator and the copy constructor. As opposed to the assignment operator, which modifies the object on the left-hand side of the assignment, the copy constructor produces a new object from an object of the same class that is passed as an argument.
Object creation: To create a new object, use the copy constructor. To assign one object to another, use the assignment operator.
Overloading: The assignment operator can be overloaded, which means that it can be redefined to perform a different action. On the other hand, the copy constructor cannot be overloaded.
Default behaviour: If a class does not have a copy constructor, the compiler will automatically generate a default copy constructor that performs a shallow copy. If a class does not have an assignment operator, the compiler automatically generates a default assignment operator that performs a shallow copy. It is important to note that the default behaviour may not be sufficient in some cases, and it is recommended to define a custom copy constructor or assignment operator.
Deep copy: It is possible to perform a shallow copy or a deep copy using the copy constructor and the assignment operator. When an object is copied, a shallow copy is made that just duplicates the values of the data members, not the actual objects they refer to. A deep copy is a copy of an object that includes a copy of the objects that the data members' values refer to as well as their own values.
Here is a tabular comparison between the copy constructor and the assignment operator in C++:
Copy constructor | Assignment operator | |
Syntax | ClassName(const ClassName& other) | ClassName& operator=(const ClassName& other) |
Purpose | Creates a new object as a copy of an existing object. | Assigns the value of an existing object to another object. |
Called automatically? | Yes, when an object is initialised with a different object of the same class. | No, it must be called explicitly by the user. |
Return Type | None | Reference to the object being assigned to. |
New Object Created? | Yes, a new object is created as a copy of the existing object. | No, the object being assigned to is modified. |
Object Initialization | Must be done during object creation. | Can be done after object creation. |
Ownership of resources | If the object contains dynamically allocated resources, the copy constructor should properly allocate new resources. | The assignment operator is responsible for releasing any resources owned by the object being assigned to and properly replicating any resources belonging to the object being assigned from. |
Conclusion:
In conclusion, the copy constructor and the assignment operator are important features in C++ that allow us to manipulate objects.
The copy constructor is used to create a new object and initialize it using the values of another object. The assignment operator, on the other hand, is utilized to assign one object to another.
It is important to understand the difference between the two and choose the appropriate method to copy objects, depending on the requirement.