Before starting assignment operator overloading, lets have a look at operator overloading in C++. In object-oriented programming, operator overloading—less commonly known as operator ad hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both. Operator overloading is used because it allows the developer to program using notation closer to the target domain and allows user-defined types a similar level of syntactic support as types built into the language. It is common, for example, in scientific computing, where it allows computational representations of mathematical objects to be manipulated with the same syntax as on paper. Object overloading can be emulated using function calls.
Now how we overload assignment operator (=),
After we do this 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:
// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;
class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
idNum = 0, salary = 0.0;
}
void setValues (int a, int b);
void operator= (Employee &emp );
};
void Employee::setValues ( int idN , int sal )
{
salary = sal; idNum = idN;
}
void Employee::operator = (Employee &emp) // Assignment operator overloading function
{
salary = emp.salary;
}
int main ( )
{
Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator
}
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 “ = ”.