🔹 Friend Functions and Classes
**Friend functions** and **friend classes** in **Object-Oriented Programming (OOP)** provide a way to **grant special access** to private and protected members of a class without using traditional getters and setters.
📌 Why Use Friend Functions?
Friend functions allow controlled access to **private** and **protected** members of a class.
- ✅ **Encapsulation with Controlled Access** – Maintains data privacy while allowing necessary access.
- ✅ **Better Inter-Class Collaboration** – Useful when two classes need close interaction.
- ✅ **Flexibility** – Allows non-member functions to access private data.
💡 Real-Life Example
Consider a **Bank Account** class where an external function calculates interest but requires access to private balance data.
🖥️ Friend Functions in C++
In C++, we use the `friend` keyword to grant function access to private members.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double b) : balance(b) {}
friend void showBalance(const BankAccount& acc);
};
void showBalance(const BankAccount& acc) {
cout << "Balance: " << acc.balance << endl;
}
int main() {
BankAccount account(1000);
showBalance(account);
return 0;
}
🖥️ Friend Classes in C++
Friend classes allow another class to access private data.
class Account {
private:
double balance;
public:
Account(double b) : balance(b) {}
friend class Auditor;
};
class Auditor {
public:
void checkBalance(const Account& acc) {
cout << "Auditor checking balance: " << acc.balance << endl;
}
};
int main() {
Account acc(5000);
Auditor auditor;
auditor.checkBalance(acc);
return 0;
}
🎯 Summary
**Friend functions and friend classes** provide a way to **bypass encapsulation in controlled situations**, enabling inter-class collaboration while maintaining **data privacy**.