Assignment Operator Overloading in C++

0
330

After we do assignment operator overloading, we will then be able to assign two variables of our self-defined datatypes. Lets have a look at the below example:

  1. // Operator overloading in C++
  2. //assignment operator overloading
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. class Employee
  7. {
  8. private:
  9.     int idNum;
  10.     double salary;
  11. public:
  12.     Employee ( ) {
  13.         idNum = 0, salary = 0.0;
  14.     }
  15.  
  16.     void setValues (int a, int b);
  17.     void operator= (Employee&emp );
  18.  
  19. };
  20.  
  21. void Employee::setValues ( int idN , int sal )
  22. {
  23.  
  24.     salary = sal; idNum = idN;
  25.  
  26. }
  27.  
  28. void Employee::operator = (Employee&emp)  // Assignment operator function
  29. {
  30.     salary = emp.salary;
  31. }
  32.  
  33. int main ( )
  34. {
  35.  
  36.     Employee emp1;
  37.     emp1.setValues(10,33);
  38.     Employee emp2;
  39.     emp2 = emp1;        // emp2 is calling object using assignment operator
  40.  
  41. }

Now lets explain this code for overloading “=” operator, we assigned the values to “idN” and “sal” by using the function “setValues” which is a public member function of the class “Employee”, Now our main point is the overloaded function which is defined as “operator =”. Inside this function we assigned the value of salary into the other variable that of the same class, Such that we could use the assignment operator directly in our main() function. Now as you can see in main(), we have two variables emp1 and emp2 of type Employee and we can use the assignment operator directly in our last line of code, It is all because of assignment operator overloading or operator overloading of operator “ = ”.