A friend function in C++ is a function that is not a member of a class, but has the ability to access the private and protected members of that class. It is declared inside the class using the keyword friend.
About Friend Functions
1. A friend function is not a member of the class.
2. It can access private and protected members of the class.
3. It is often used when a function needs to operate on multiple classes or interact with private members of a class, but doesn’t belong to the class itself.
Example:
#include <iostream>
using namespace std;
class Employee {
private:
string name;
int age;
public:
// Constructor to initialize values
Employee(string n, int a) : name(n), age(a) {}
// Friend function declaration
friend void displayEmployeeInfo(Employee emp);
};
// Friend function definition
void displayEmployeeInfo(Employee emp) {
cout << "Name: " << emp.name << endl; // Accessing private member 'name'
cout << "Age: " << emp.age << endl; // Accessing private member 'age'
}
int main() {
// Creating a Employee object
Employee employee("John", 35);
// Calling the Employee function
displayEmployeeInfo(employee); // This can access the private members of 'Employee'
return 0;
}
Output:
Name: John
Age: 35
Age: 35
Explanation:
1. Employee Class:
- It has two private data members: name and age.
- It has a constructor to initialize these members.
2. Friend Function displayEmployeeInfo():
- This function is declared as a friend of the Employee class, meaning it can access the private members (name and age) of any Employee object.
- It prints the private information of the Employee object passed to it.
3. In main():
- A Employee object employee is created.
- The friend function displayEmployeeInfo() is called, and it can access the private members of the employee object.