Protected members can also be accessed by friend functions. I don't know if friend functions are used much in the real world, our instructor doesn't like them, but the Deitel text uses them for overloaded << operators on classes.
As can private members. Friend functions are necessary when you want to use the member function of an object on the right of a binary expression.
If you overloaded the << operator for ouput inside the class (rather than as a friend function), you'd have to do something like -
Code:
class Adult
{
protected:
int var1;
public:
void SetVar1(int i){var1=i;}
ostream& operator<<(ostream& os){return os << var1;}
};
int main()
{
Adult me;
me.SetVar1(27);
me << cout;
return 0;
}
as the Adult object has to be on the left. If you use a friend function you can put the ostream of the left -
Code:
class Adult
{
private:
int var1;
public:
void SetVar1(int i){var1=i;}
friend ostream& operator<<(ostream& os,Adult& a);
};
ostream& operator <<(ostream& os,Adult& a)
{
return os << a.var1;
}
int main()
{
Adult me;
me.SetVar1(27);
cout << me;
return 0;
}