The answer is same as Copy Constructor. If a class doesn’t contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or any run time allocation of resource like file handle, a network connection..etc. For example, consider the following program.
Output of above program is “10”. If we take a look at main(), we modified ‘t1’ using setValue() function, but the changes are also reflected in object ‘t2’. This type of unexpected changes cause problems.
Since there is no user defined assignment operator in the above program, compiler creates a default assignment operator, which copies ‘ptr’ of right hand side to left hand side. So both ‘ptr’s start pointing to the same location.
We can handle the above problem in two ways.
1) Do not allow assignment of one object to other object. We can create our own dummy assignment operator and make it private.
2) Write your own assignment operator that does deep copy.
Same is true for Copy Constructor.
Following is an example of overloading assignment operator for the above class.
We should also add a copy constructor to the above class, so that the statements like “Test t3 = t4;” also don’t cause any problem.
Note the if condition in assignment operator. While overloading assignment operator, we must check for self assignment. Otherwise assigning an object to itself may lead to unexpected results (See this). Self assignment check is not necessary for the above ‘Test’ class, because ‘ptr’ always points to one integer and we may reuse the same memory. But in general, it is a recommended practice to do self-assignment check.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Self assignment check in assignment operator
- Is assignment operator inherited?
- Default Assignment Operator and References
- Copy constructor vs assignment operator in C++
- Assignment Operators in C/C++
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Write a URL in a C++ program
- How to write your own header file in C?
- Write a C program that won't compile in C++
- When should we write our own copy constructor?
- Write your own memcpy() and memmove()
- Write a program that produces different results in C and C++
- How to write a running C code without main()?
- C program to write an image in PGM format
- Read/Write structure to a file in C