• Register
100 points
7 4

Operator overloading provides an inherent interface to the users of our class, making it possible to work equally well with classes and built-in data types. Operator overloading in C++ allows operators to have user-defined meanings on user defined types.
This article will discuss overloading using friend functions.

There are three methods to do operator overloading in C++, they are

  1. Overloading unary operators.
  2. Overloading binary operator.
  3. Overloading binary operator using a friend function.

And we are going to discuss only overloading binary operators using a friend function.

The function which has the right to access all private and protected members of the class but defined outside the scope of the class, is called friend function.

How to do operator overloading using friend function?


In this method, the operator overloading function will precede with the keyword friend. The friend operator function will take two parameters in a binary operator. All of the working will be the same as the binary operator function except the thing that it will be implemented outside of the class scope.

Program

#include <iostream> 
  
using namespace std; 
  
class Distance { 
public: 
  
    // Member Object 
    int feet, inch; 
  
    // No Parameter Constructor 
    Distance() 
    { 
        this->feet = 0; 
        this->inch = 0; 
    } 
  
    // Constructor to initialize the object's value 
    // Parametrized Constructor 
    Distance(int f, int i) 
    { 
        this->feet = f; 
        this->inch = i; 
    } 
  
    // Declaring friend function using friend keyword 
    friend Distance operator+(Distance&, Distance&); 
}; 
  
// Implementing friend function with two parameters 
Distance operator+(Distance& d1, Distance& d2) // Call by reference 
{ 
    // Create an object to return 
    Distance d3; 
  
    // Perform addition of feet and inches 
    d3.feet = d1.feet + d2.feet; 
    d3.inch = d1.inch + d2.inch; 
  
    // Return the resulting object 
    return d3; 
} 
  
// Driver Code 
int main() 
{ 
    // Declaring and Initializing first object 
    Distance d1(8, 9); 
  
    // Declaring and Initializing second object 
    Distance d2(10, 2); 
  
    // Declaring third object 
    Distance d3; 
  
    // Use overloaded operator 
    d3 = d1 + d2; 
  
    // Display the result 
    cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch; 
    return 0; 
}

Hope this will help.

100 points
7 4