Friend Functions
A friend function is a non-member function that has access to a class's private and protected members.
Declare it inside the class with the friend keyword.
When to Use
Friend functions are useful for operator overloading and when two classes need tight cooperation. They break encapsulation, so use them sparingly.
#include <iostream>
using namespace std;
class Box {
private:
double length;
public:
Box(double l) {
length = l;
}
friend void printLength(Box b);
};
void printLength(Box b) {
cout << "Length: " << b.length << "\n";
}
int main() {
Box box(10.5);
printLength(box);
return 0;
}
Try it Yourself →