In C++, a friend function is a function that is declared inside a class and has access to its private and protected members, even though it is not a member function of the class. A friend function can be either a standalone function or a member function of another class.
The syntax for declaring a friend function is as follows:
class MyClass {
friend ReturnType functionName(parameters);
// ...
};
The friend function declaration must appear inside the class definition, but the definition of the friend function can appear outside the class definition. When the friend function is called, it can access the private and protected members of the class as if they were its own members.
For example:
class MyClass {
private:
int x;
public:
MyClass(int x) : x(x) {}
friend void printX(MyClass obj);
};
void printX(MyClass obj) {
std::cout << "x = " << obj.x << std::endl;
}
int main() {
MyClass obj(10);
printX(obj);
return 0;
}
In this example, the printX() function is declared as a friend of the MyClass class. When the printX() function is called, it can access the private member x of the MyClass object passed as a parameter.
Friend functions are useful when you need to provide external functions with access to the private members of a class, without making those members public. However, they should be used sparingly, as they can potentially violate the encapsulation of the class and make the code less maintainable.