Performing Operator Overloading in C++ with example

0
47
Operator overloading in C++
Creating Overloaded operator in C++ with example

As we know The variables of primitive data types can perform a number of different operations (functions) using operators like (+, – , /, *)/

For Example: a + b * c or if ( a < b )

However in used defined datatypes we cannot do such operations

For Example: class obj1,obj2;
if(obj1<obj2)

this is not possible in this case, we need the concept of operator overloading here.


Now for the syntax we first have to create a function for the class, for example:

operator+ for the addition operator ‘+’
operator> for the comparison operator ‘>’

In operator overloading the Operators are mostly like functions, they can take arguments and can return values, the only thing that separates them from ordinary functions is their specified name and syntax at the time of definition and we cannot create our own operator, otherwise we can overload it.

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 overloading 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 operator overloading of operator “ = ”.

Operator overloading in C++
Creating Overloaded operator in C++ with example

Leave a Reply