Friends have access to the private parts
A friend can be a function, a method, or an entire class (all its methods)
Friends have good uses:
Simulating package visibility
Increasing encapsulation
Friends have bad uses:
Indiscrimate violation of encapsulation
Performance hacks
(See template notes for template friends)
A Friend of a Friend is not a Friend
Example: implementing an output stream insertion operator
#include <iostream.h>
#include <string.h>
const int MAX_CHAR = 10;
class BankAccount {
friend ostream&
operator<<(ostream& o, BankAccount &b);
public:
BankAccount
( char* name ="unknown", char * mr = "Miss", float y=0.0)
{
title = mr;
strcpy(owner, name);
balance = y;
}
private:
char * title;
char
owner[MAX_CHAR];
float
balance;
};
ostream& operator<< (ostream& o,
BankAccount &b)
{
o <<"who:"<< b.title <<
" " << b.owner<<" how much="<< b.balance<<"\n";
o << endl;
return o;
}
void main(){
BankAccount acc("Lou","Mr", 100);
cout << acc;
}
#include <iostream.h>
#include <string.h>
const int MAX_CHAR = 10;
class BankAccount {
public:
BankAccount
( char* name ="unknown", char * mr = "Miss", float y=0.0)
{
title = mr;
strcpy(owner, name);
balance = y;
}
void
print(ostream& o)
{
o <<"who:"<< title << " " << owner<<" how
much="<< balance<<"\n"; }
private:
char * title;
char
owner[MAX_CHAR];
float
balance;
};
//notice use of references -to be discussed later
ostream& operator<< (ostream& o,
BankAccount &b) //notice pass by reference
{
b.print(o);
o << endl;
return o;
}
void main(){
BankAccount acc("Lou","Mr", 100);
cout << acc;
}
Example: BankAccount with friend class Bank
#include <iostream.h>
#include <string.h>
const int MAX_CHAR = 10;
class BankAccount {
friend ostream& operator<<(ostream&
o, BankAccount &b);
friend class Bank;
public:
BankAccount
( char* name ="unknown", char * mr = "Miss", float y=0.0)
{
title = mr;
strcpy(owner, name);
balance = y;
}
private:
char * title;
char
owner[MAX_CHAR];
float
balance;
};
ostream& operator<< (ostream& o,
BankAccount &b)
{
o <<"who:"<< b.title <<
" " << b.owner<<" how much="<< b.balance<<"\n";
o << endl;
return o;
}
class Bank{
public:
void deposit(BankAccount & b, float
amount){b.balance += amount;}
void withdraw(BankAccount & b, float
amount){b.balance -= amount;}
};
void main(){
BankAccount acc("Lou","Mr", 100);
Bank theBank;
theBank.deposit(acc,500);
cout << acc;
}