Operator Overloading Using Friend Function
Similar to the above approach where we defined the overload function outside the class definition, we can define that function as a friend when we want our operator function to modify the value of the private data members.
Again, the binary operator function will take two arguments and the unary operator function will take one argument as the function is defined outside the class and there will be no this pointer.
Note: Apart from the case where we need the operator function to give access to the private memebers, we should not use the friend function to prevent the exposure of private members to public API.
Example of Operator Overloading Using Friend Function
// C++ program to show operator overloading using
// a Friend Function
#include <iostream>
using namespace std;
class Distance {
int feet, inch;
public:
Distance(): feet(0), inch(0) {}
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// getter functions
int getFeet() { return this->feet; }
int getInch() { return this->inch; }
// Declaring friend function
// using friend keyword
friend Distance operator+(Distance&, Distance&);
};
// Implementing friend function
// with two parameters
// Call by reference
Distance operator+(Distance& d1, Distance& d2)
{
// Create an object to return
Distance d3;
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
// Return the resulting object
return d3;
}
// Driver Code
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " << d3.getFeet() << "'"
<< d3.getInch();
return 0;
}
Output
Total Feet & Inches: 18'11
Operators that cannot be overloaded when declaring that function as friend function are = () [] ->.
Different Ways of Operator Overloading in C++
In C++, operator overloading is the concept that allows us to redefine the behavior of the already existing operator for our class. C++ provides a special function called operator function that can be used to achieve operator overloading.
In this article, we will learn the different ways in which we can define the operator function for operator overloading in C++.