How can a friend class access the private members of another class?
When a class has declared another class as a friend, how can that friend class access the private members of the other class?
I mean, I thought the function of the friend class have complete access to the private members of the other class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
using namespace std;
class Food
{
friend class Drink
string favoriteFood;
public:
void changeFavorite ()
{
favoriteFood = "pizza";
}
};
class Food;
class Drink
{
public:
void useMembers ()
{
favoriteFood = "cheese"; //shouldn't this function have access to the private member favoriteFood?
}
};
|
Yes, but of which food? Consider this usage:
1 2 3 4 5
|
Food apple;
Food beef;
Drink bar;
bar.useMembers(); // Whose favoriteFood? Of apple? Of beef? Of bar?
|
Topic archived. No new replies allowed.