My understanding was that a friend class can access all of the members (including data members) of the base. However, with this code:
class Animal {
string _name;
Animal(){};
Animal(const string & n, const string & t, const string & w);
friend class Duck;
};
Animal::Animal(const string & n) : _name(n) {
}
class Duck: public Animal {
public:
Duck(const string n) : Animal(n){};
};
int main(int argc, char *argv[])
{
Duck donald("Donny");
printf("The donlad ran %s\n", donald._name.c_str());
return 0;
}
I get error: '_name' is a private member of 'Animal'
Why can't the friend class Duck
access all the members of the base class Animal
?
The error is where you call
printf("The donlad ran %s\n", donald._name.c_str());
inmain
You can't access
_name
via a class instance (donald
in this case) because_name
isprivate
._name
is accessible from within theDuck
class because of thefriend
designation, but is not accessible inmain