Friend functions offer a way to grant specific access to private or protected members of a class without making those members public. Here’s when to use friend functions over public members:
operator<<
), friend functions can access the private data needed for the operation.Consider a BankAccount
class where we want to allow a transferFunds
function to access private balance data:
#include <iostream>
class BankAccount {
friend void transferFunds(
BankAccount &from,
BankAccount &to,
double amount
);
public:
BankAccount(double balance)
: balance{balance} {}
void displayBalance() const {
std::cout << "Balance: " << balance << "\n";
}
private:
double balance;
};
void transferFunds(
BankAccount &from,
BankAccount &to,
double amount
) {
if (from.balance >= amount) {
from.balance -= amount;
to.balance += amount;
}
}
int main() {
BankAccount account1{100.0};
BankAccount account2{50.0};
transferFunds(account1, account2, 30.0);
account1.displayBalance(); // Balance: 70
account2.displayBalance(); // Balance: 80
}
Balance: 70
Balance: 80
In this example, transferFunds
is a friend function that transfers money between two accounts.
Making balance
public would expose it unnecessarily, while the friend function provides the needed access without compromising encapsulation.
Friend functions offer a balance between encapsulation and accessibility, but use them only when it makes logical and structural sense.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members