Copy Constructor vs Assignment Operator in C++ - Differences with Examples
In C++, objects of a class can be copied in different ways. Two commonly used mechanisms are the Copy Constructor and the Assignment Operator. Although both are used to copy data from one object to another, they work at different stages. A copy constructor initializes a new object using an existing object, whereas the assignment operator copies values into an object that has already been created.
C++ में एक object का data दूसरे object में copy करने के लिए Copy Constructor और Assignment Operator का उपयोग किया जाता है। दोनों का उद्देश्य data copy करना है, लेकिन इनके काम करने का तरीका अलग होता है।
1. What is a Copy Constructor in C++?
A copy constructor is a special constructor that creates a new object by initializing it from another object of the same class.
Its commonly used syntax is:
ClassName(const ClassName& object) {// Copy data members}
The copy constructor takes a reference to an existing object of the same class, usually as a const reference.
C++ में Copy Constructor एक special constructor होता है, जो किसी existing object के आधार पर नया object initialize करता है।
Example of Copy Constructor
#include <iostream>using namespace std;class Student {int rollNo;float marks;public:Student(int r, float m) {rollNo = r;marks = m;}Student(const Student& s) {rollNo = s.rollNo;marks = s.marks;cout << "Copy Constructor Called" << endl;}void display() {cout << "Roll Number: " << rollNo << endl;cout << "Marks: " << marks << endl;}};int main() {Student s1(101, 85.5f);Student s2 = s1;cout << "\nOriginal Object:" << endl;s1.display();cout << "\nCopied Object:" << endl;s2.display();return 0;}
Output
Copy Constructor CalledOriginal Object:Roll Number: 101Marks: 85.5Copied Object:Roll Number: 101Marks: 85.5
Explanation
In this program:
Student s1(101, 85.5f);creates the first object using a parameterized constructor.Student s2 = s1;creates a new objects2by copyings1.The copy constructor is called to initialize
s2.Both objects contain the same initial data values.
इस program में s1 एक existing object है। Statement Student s2 = s1; एक नया object s2 बनाता है और उसे s1 के data से initialize करता है। इस प्रक्रिया में Copy Constructor call होता है।
2. What is an Assignment Operator in C++?
The assignment operator (=) is used to assign the values of one object to another object that has already been created.
For class objects, C++ provides a compiler-generated copy assignment operator unless certain conditions prevent its implicit declaration or use. We can also define our own copy assignment operator.
Syntax of Assignment Operator
object1 = object2;The statement assigns the contents of object2 to the already existing object1.
C++ में Assignment Operator (=) का उपयोग पहले से बने हुए object में दूसरे object का data assign करने के लिए किया जाता है।
Example of Assignment Operator
#include <iostream>using namespace std;class Student {int rollNo;float marks;public:Student(int r, float m) {rollNo = r;marks = m;}void display() {cout << "Roll Number: " << rollNo << endl;cout << "Marks: " << marks << endl;}};int main() {Student s1(101, 85.5f);Student s2(102, 70.0f);s2 = s1;cout << "Original Object:" << endl;s1.display();cout << "\nAssigned Object:" << endl;s2.display();return 0;}
Output
Original Object:Roll Number: 101Marks: 85.5Assigned Object:Roll Number: 101Marks: 85.5
Explanation
In this program:
s1ands2are created using the parameterized constructor.Both objects already exist before the assignment statement.
s2 = s1;copies the values froms1into the existing objects2.The compiler-generated copy assignment operator performs memberwise assignment in this example.
इस program में दोनों objects पहले से create हो चुके हैं। Statement s2 = s1; के द्वारा s1 का data existing object s2 में copy किया जाता है। यहाँ Copy Constructor call नहीं होता, बल्कि Copy Assignment Operator का उपयोग होता है।
3. Difference Between Copy Constructor and Assignment Operator in C++
The following table explains the major differences between a copy constructor and an assignment operator.
| Copy Constructor | Assignment Operator |
|---|---|
| It initializes a new object from an existing object. | It assigns values to an already existing object. |
| It is a special constructor. | It is an overloaded operator function. |
| It is called during copy initialization or direct initialization from another object. | It is called when the assignment operator is used between existing objects. |
It is generally written as ClassName(const ClassName& obj). | A copy assignment operator is generally written as ClassName& operator=(const ClassName& obj). |
| It does not have a return type. | A user-defined copy assignment operator commonly returns a reference to the current object. |
| It is used to initialize a new object. | It is used to modify an existing object. |
| It can be overloaded in certain forms. | Assignment operators can be overloaded. |
4. Copy Constructor vs Assignment Operator – Program Demonstration
The following program demonstrates both mechanisms in the same class.
C++ Program
#include <iostream>using namespace std;class Number {int value;public:Number(int v) {value = v;}// Copy ConstructorNumber(const Number& n) {value = n.value;cout << "Copy Constructor Called" << endl;}// Copy Assignment OperatorNumber& operator=(const Number& n) {cout << "Assignment Operator Called" << endl;if (this != &n) {value = n.value;}return *this;}void display() {cout << "Value: " << value << endl;}};int main() {Number n1(100);// Copy ConstructorNumber n2 = n1;// Assignment OperatorNumber n3(200);n3 = n1;cout << "\nObject n1:" << endl;n1.display();cout << "\nObject n2:" << endl;n2.display();cout << "\nObject n3:" << endl;n3.display();return 0;}
Output
Copy Constructor CalledAssignment Operator CalledObject n1:Value: 100Object n2:Value: 100Object n3:Value: 100
Explanation
The program uses both the copy constructor and the assignment operator.
1. Copy Constructor
Number n2 = n1;This statement creates a new object n2 and initializes it using n1. Therefore, the copy constructor is called.
2. Assignment Operator
Number n3(200);n3 = n1;
Here, n3 is already created. The assignment statement copies the value of n1 into n3, so the copy assignment operator is called.
3. Self-Assignment Check
if (this != &n) {value = n.value;}
This condition checks whether the source and destination are the same object. It is a useful safeguard in many user-defined assignment operators, especially when managing dynamic resources.
इस program में Number n2 = n1; एक नया object बनाता है, इसलिए Copy Constructor call होता है। दूसरी ओर, n3 = n1; पहले से बने object में data assign करता है, इसलिए Assignment Operator call होता है।
5. Difference Between Copy Initialization and Assignment
Students often confuse the following two statements:
Student s2 = s1;and
Student s2(0);s2 = s1;
Although both involve copying data, their meanings are different.
| Statement | Meaning |
|---|---|
Student s2 = s1; | Creates a new object using copy initialization. |
Student s2(0); s2 = s1; | Creates an object first and then assigns data to it. |
Remember: The = symbol in Student s2 = s1; does not mean that the assignment operator is used. This is copy initialization, so the copy constructor is selected.
ध्यान रखें कि Student s2 = s1; में = दिखाई देने के बावजूद यह assignment operation नहीं है। यह copy initialization है और नए object को initialize करने के लिए Copy Constructor का उपयोग होता है।
6. Shallow Copy and Deep Copy
Both the copy constructor and copy assignment operator can perform shallow or deep copying, depending on how they are implemented.
Shallow Copy: A shallow copy copies member values directly. If a class contains a raw pointer, this copies the pointer address rather than creating a separate allocation.
Deep Copy: A deep copy creates separate resources for the destination object and copies the required data into them.
Shallow copy can cause problems when multiple objects incorrectly share ownership of dynamically allocated memory. Deep copying or appropriate resource management can prevent these problems.
Copy Constructor और Assignment Operator दोनों में shallow copy या deep copy की जा सकती है। यदि class में dynamically allocated memory को manage करने वाला raw pointer है, तो केवल pointer address copy करना unsafe हो सकता है।
Example: User-Defined Copy Assignment Operator
#include <iostream>using namespace std;class Number {int* value;public:Number(int v) {value = new int(v);}// Deep Copy ConstructorNumber(const Number& n) {value = new int(*n.value);}// Deep Copy Assignment OperatorNumber& operator=(const Number& n) {if (this != &n) {*value = *n.value;}return *this;}void display() {cout << "Value: " << *value << endl;}~Number() {delete value;}};int main() {Number n1(100);Number n2 = n1;Number n3(200);n3 = n1;cout << "Original Object:" << endl;n1.display();cout << "\nCopied Object:" << endl;n2.display();cout << "\nAssigned Object:" << endl;n3.display();return 0;}
Output
Original Object:Value: 100Copied Object:Value: 100Assigned Object:Value: 100
Explanation
In this example:
The copy constructor allocates separate memory for
n2.The copy assignment operator copies the value into the memory already owned by
n3.Each object owns its own dynamically allocated integer.
The destructor releases the allocated memory when each object is destroyed.
This example illustrates deep copying for a single integer resource. In real applications, resource-owning classes require careful handling of copying, assignment, destruction, and exception safety. Modern C++ generally recommends using standard library types such as std::vector, std::string, and smart pointers instead of managing raw memory manually.
इस उदाहरण में प्रत्येक object के लिए अलग memory allocate होती है। Copy Constructor नया resource बनाता है, जबकि Assignment Operator destination object के पहले से मौजूद resource में value copy करता है।
7. Frequently Asked Questions (FAQs)
Q1. What is the main difference between a copy constructor and an assignment operator?
A copy constructor initializes a new object using an existing object, whereas an assignment operator copies data into an already existing object.
Copy Constructor नया object initialize करता है, जबकि Assignment Operator existing object में data copy करता है।
Q2. Does the assignment operator call the copy constructor?
No. Assigning one existing object to another normally invokes the copy assignment operator, not the copy constructor.
नहीं, existing objects के बीच assignment करने पर सामान्यतः Copy Assignment Operator call होता है।
Q3. Can we overload the assignment operator in C++?
Yes. We can define a user-defined copy assignment operator using operator=.
हाँ, C++ में operator= का उपयोग करके Assignment Operator overload किया जा सकता है।
Q4. What happens if we do not define a copy constructor?
The compiler may implicitly declare and define a copy constructor. Its default behaviour is memberwise copying, subject to the class's members and language rules.
यदि हम Copy Constructor define नहीं करते, तो compiler परिस्थितियों के अनुसार implicit copy constructor provide कर सकता है, जो सामान्यतः memberwise copying करता है।
Q5. What happens if we do not define an assignment operator?
The compiler may provide an implicit copy assignment operator, which generally performs memberwise assignment.
यदि हम अपना Copy Assignment Operator define नहीं करते, तो compiler सामान्यतः implicit copy assignment operator provide कर सकता है।
Q6. What is self-assignment?
Self-assignment occurs when an object is assigned to itself, such as:
n1 = n1;A carefully designed assignment operator should handle this case safely.
जब किसी object को उसी object में assign किया जाता है, तो इसे Self-Assignment कहते हैं।
The copy constructor and assignment operator are both important features of C++ object-oriented programming. The copy constructor is used when a new object is initialized from an existing object, while the assignment operator is used when an existing object receives data from another object. Understanding this distinction is especially important when working with pointers, dynamic memory allocation, and resource-owning classes.
C++ में Copy Constructor और Assignment Operator दोनों objects के बीच data copying के लिए उपयोगी हैं। इनका मुख्य अंतर यह है कि Copy Constructor नया object initialize करता है, जबकि Assignment Operator पहले से मौजूद object को modify करता है।
Comments
Post a Comment