C++ Overloading assignment operator



We already know the assignment operator in C++. In this tutorial we will be learning concept of C++ Overloading assignment operator.

Assignment operator in C++

  1. Assignment Operator is Used to assign value to an variable.
  2. Assignment operator is denoted by equal to sign.
  3. Assignment operator have Two values L-Value and R-value. Operator copies R-Value into L-Value.
  4. It is a binary operator.

C++ Overloading Assignment Operator

  1. C++ Overloading assignment operator can be done in object oriented programming.
  2. By overloading assignment operator, all values of one object (i.e instance variables) can be copied to another object.
  3. Assignment operator must be overloaded by a non-static member function only.
  4. If the overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator.

Syntax

Return_Type operator = (const Class_Name &)

Way of overloading Assignment Operator

#include<iostream>
using namespace std;
 
class Marks
{
   private:
      int m1;            
      int m2;           
   
   public:

   //Default constructor
   Marks() {
        m1 = 0;
        m2 = 0;
   }
   
   // Parametrised constructor
    Marks(int i, int j) {
        m1 = i;
        m2 = j;
    }

   // Overloading of Assignment Operator
    void operator=(const Marks &M ) { 
        m1 = M.m1;
        m2 = M.m2;
    }
    
   void Display() {
      cout << "Marks in 1st Subject:" << m1;
      cout << "Marks in 2nd Subject:" << m2;
    }   
};

int main()
{
  // Make two objects of class Marks
   Marks Mark1(45, 89);
   Marks Mark2(36, 59); 
   
   cout << " Marks of first student : "; 
   Mark1.Display();
   cout << " Marks of Second student :"; 
   Mark2.Display();

   // use assignment operator
   Mark1 = Mark2;
   
   cout << " Mark in 1st Subject :"; 
   Mark1.Display();

   return 0;
}

Explanation

 private:
      int m1;            
      int m2;  

Here, in Class Marks contains private Data Members m1 and m2.

Marks Mark1(45, 89);
Marks Mark2(36, 59);

In the main function, we have made two objects ‘Mark1’ and ‘Mark2’ of class ‘Marks’. We have initialized values of two objects using parametrised constructor.

void operator=(const Marks &M ) { 
	m1 = M.m1;
	m2 = M.m2;
}

As shown in above code, we overload the assignment operator, Therefore, ‘Mark1=Mark2’ from main function will copy content of object ‘Mark2’ into ‘Mark1’.

Output

Marks of first student : 
Mark in 1st Subject : 45 
Marks in 2nd Subject : 89

Marks of Second student : 
Mark in 1st Subject : 36 
Marks in 2nd Subject : 59

Marks of First student : 
Mark in 1st Subject : 36 
Marks in 2nd Subject : 59