When should we write our own assignment operator in C++ programming?


Here we will see when we need to create own assignment operator in C++. If a class do not have any pointers, then we do not need to create assignment operator and copy constructor. C++ compiler creates copy constructor and assignment operator for each class. If the operators are not sufficient, then we have to create our own assignment operator.

Example

#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
      void setValue (int x) {
         *ptr = x;
      }
      void print() {
         cout << *ptr << endl;
      }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}

Output

100

In the main() function, we have set the value of x using setValue() method for ob1. The value is also reflected in object ob2; This type of unexpected changes may generate some problems. There is no user defined assignment operator, so compiler creates one. Here it copies the ptr of RHS to LHS. So both of the pointers are pointing at the same location.

To solve this problem, we can follow two methods. Either we can create dummy private assignment operator to restrict object copy, otherwise create our own assignment operator.

Example

#include<iostream>
using namespace std;
class MyClass { //no user defined assignment operator or copy constructor is present
   int *ptr;
   public:
      MyClass (int x = 0) {
         ptr = new int(x);
      }
      void setValue (int x) {
         *ptr = x;
      }
      void print() {
         cout << *ptr << endl;
      }
      MyClass &operator=(const MyClass &ob2){
      // Check for self assignment
         if(this != &ob2)
            *ptr = *(ob2.ptr);
         return *this;
      }
};
main() {
   MyClass ob1(50);
   MyClass ob2;
   ob2 = ob1;
   ob1.setValue(100);
   ob2.print();
}

Output

50

Here the assignment operator is used to create deep copy and store separate pointer. One thing we have to keep in mind. We have to check the self-reference otherwise the assignment operator may change the value of current object.

Updated on: 18-Dec-2019

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements