Assignment Operator Overloading in C++

Assignment Operators Overloading in C++

What is assignment operator overloading in C++?

Assignment operator is a binary operator that is used to assign the value to the variables. It is represented by equal to symbol(=). It copies right value into the left value i.e the value that is on the right side of equal to into the variable that is on the left side of equal to.

In this article, we will learn more about assignment operator overloading in C++ , And if you want to know more about operator overloading you can learn simply by click the button below.

Overloading assignment operator in C++

Overloading assignment operator in C++ copies all values of one object to another object. The object from which values are being copied is known as an instance variable. A non-static member function should be used to overload the assignment operator.

The compiler generates the function to overload the assignment operator if the function is not written in the class. Overloading assignment operator can be used to create an object just like the copy constructor. If a new object does not have to be created before the copying occurs, the assignment operator is used, and if the object is created then copy constructor will come into the picture. Below is a program to explain how the assignment operator overloading works.


C++ program demonstrating assignment operator overloading

#include <iostream>
using namespace std;
 
class Length 
{
   private:
      int kmeter;            
      int meter;           
      
   public:
     
      Length() //default constructor 
      {
         kmeter = 0;
         meter = 0;
      }
      Length(int km, int m)  //overloaded constructor.
      {
         kmeter= km;
         meter = m;
      }
      void operator = (const Length &l ) 
      { 
         kmeter = l.kmeter;
         meter = l.meter;
      }
      
      //method to display length.
      void disLength() 
      {
         cout <<kmeter<<"Km "<<meter<<"M"<< endl;
      }
};

int main() 
{
   Length l1(1, 112), l2(2, 27);

   cout <<"First length: "; 
   l1.disLength();
   cout <<"Second length:"; 
   l2.disLength();

   //overloading assignment operator.
   l1 = l2;
   cout << "First Length :"; 
   l1.disLength();

   return 0;
}
Output:
First length: 1Km 112M
Second length: 2Km 27M
First Length: 2Km 27M