In C++, a friend function is a function that is not a member of a class but has access to its private and protected members. This allows the friend function to access the internal state of the class directly, which can be useful for certain operations that require access to private data.
Here are some key points about friend functions:
-
Declaration: A friend function is declared within the class using the
friendkeyword. This declaration allows the function to access the class's private and protected members. -
Not a Member: Although it has access to the class's private members, a friend function is not a member of the class. It can be a standalone function or a member of another class.
-
Multiple Friends: A class can have multiple friend functions, and friend functions can also be friends of multiple classes.
-
Use Cases: Friend functions are often used for operator overloading, where you need to access private members of two different classes.
Here’s a simple example demonstrating the use of a friend function:
#include <iostream>
using namespace std;
class Box {
private:
double width;
public:
Box(double w) : width(w) {}
// Declare friend function
friend void printWidth(Box box);
};
// Friend function definition
void printWidth(Box box) {
cout << "Width of box: " << box.width << endl;
}
int main() {
Box box(10.5);
printWidth(box); // Accessing private member width
return 0;
}
In this example, the printWidth function is a friend of the Box class, allowing it to access the private member width. When you run this code, it will output:
Width of box: 10.5
This demonstrates how a friend function can access private data of a class.
