Friend Function in C++
In C++, a friend function of a class is a function that can access all the private and protected members of the class. This function is not a member of the class, but is declared as a friend of the class.
Syntax
The syntax for declaring a friend function in C++ is as follows:
class ClassName {
friend returnType functionName(arguments);
//...
};
The friend function declaration should be placed inside the class declaration but the function definition should be outside the class declaration.
class ClassName {
friend returnType functionName(arguments);
//...
};
returnType ClassName::functionName(arguments) {
// code
}
Example
#include <iostream>
using namespace std;
class MyClass {
int num;
public:
MyClass(int n) {
num = n;
}
friend void printNum(MyClass obj);
};
void printNum(MyClass obj) {
cout << "Num: " << obj.num << endl;
}
int main() {
MyClass obj(42);
printNum(obj);
return 0;
}
Output
Num: 42
Explanation
In the above example, we have defined a class named "MyClass" with a private member variable "num". We have also defined a friend function called "printNum" that can access the private member variable of the class. We create an instance of the class and pass it to the friend function for display.
Use
Friend functions are useful when you need to access private or protected members of a class from outside the class. This can simplify function implementation and improve encapsulation.
Important Points
- Friend functions are not members of a class but can access its private and protected members.
- Friend functions should be explicitly declared as friends of a class.
- Friend functions can be defined outside the class declaration.
Summary
In summary, friend functions in C++ are a powerful tool for accessing private and protected members of a class. They can simplify function implementation and improve encapsulation. However, they should be used sparingly and only when necessary, as they can reduce the benefits of encapsulation and make code harder to maintain.