When a friend function is overloaded, each version of the function must be declared as a friend within the class. This ensures that each overloaded variant has the necessary access to the class's private and protected members.
Consider a class Example
with overloaded friend functions:
#include <iostream>
class Example {
friend void display(const Example &obj);
friend void display(
const Example &obj, int extra);
private:
int value{5};
};
void display(const Example &obj) {
std::cout << "Value: "
<< obj.value << "\n";
}
void display(const Example &obj, int extra) {
std::cout << "Value: "
<< obj.value + extra << "\n";
}
int main() {
Example ex;
display(ex);
display(ex, 10);
}
Value: 5
Value: 15
In this example, both display()
functions are declared as friends of Example
. Each function can access the private member value
.
When you overload friend functions, you must ensure that their signatures are distinct enough to avoid ambiguity. The compiler uses the number and types of parameters to differentiate between overloaded functions.
Friend functions are often used to overload operators. Here's an example of overloading the +
operator for a Vector
 class:
#include <iostream>
class Vector {
friend Vector operator+(
const Vector &v1, const Vector &v2);
friend std::ostream &operator<<(
std::ostream &os, const Vector &v);
public:
Vector(int x, int y) : x{x}, y{y} {}
private:
int x, y;
};
Vector operator+(
const Vector &v1, const Vector &v2) {
return Vector(v1.x + v2.x, v1.y + v2.y);
}
std::ostream &operator<<(
std::ostream &os, const Vector &v) {
os << "Vector(" << v.x << ", " << v.y << ")";
return os;
}
int main() {
Vector v1(1, 2);
Vector v2(3, 4);
Vector v3 = v1 + v2;
std::cout << v3;
}
Vector(4, 6)
In this example, the +
operator is overloaded using a friend function, allowing it to access the private members of the Vector
 class.
Overloading friend functions is straightforward, but each overloaded variant must be explicitly declared as a friend. This ensures that all versions have the necessary access to the class's private and protected members.
Overloading is particularly useful in scenarios like operator overloading, where different versions of a function need to handle various types or numbers of parameters.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members