In C++, assignment operator should be overloaded with self assignment check.
For example, consider the following class Array and overloaded assignment operator function without self assignment check.
If we have an object say a1 of type Array and if we have a line like a1 = a1 somewhere, the program results in unpredictable behavior because there is no self assignment check in the above code. To avoid the above issue, self assignment check must be there while overloading assignment operator. For example, following code does self assignment check.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Copy constructor vs assignment operator in C++
- Is assignment operator inherited?
- When should we write our own assignment operator in C++?
- Default Assignment Operator and References
- vector::operator= and vector::operator[ ] in C++ STL
- deque::operator= and deque::operator in C++ STL
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Operator Overloading '<<' and '>>' operator in a linked list class
- 3-way comparison operator (Space Ship Operator) in C++ 20
- Quine - A self-reproducing program
- Can a C++ class have an object of self type?
- Operands for sizeof operator
- Rules for operator overloading
- Result of comma operator as l-value in C and C++
- Comma operator should be used carefully
- C/C++ Ternary Operator - Some Interesting Observations
- Can we use % operator on floating point numbers?
- Set a variable without using Arithmetic, Relational or Conditional Operator
- Placement new operator in C++
- Operator Overloading in C++