Reputation: 13206
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
?
Upvotes: 2
Views: 68
Reputation: 6039
The error is where you call printf("The donlad ran %s\n", donald._name.c_str());
in main
You can't access _name
via a class instance (donald
in this case) because _name
is private
. _name
is accessible from within the Duck
class because of the friend
designation, but is not accessible in main
Upvotes: 2
Reputation: 3260
friend
has nothing to do with inheritance.
You get the error because main()
, not Duck
, is the one trying to access the private _name
member of Animal
. Making Duck
a friend
of Animal
grants access to Duck
's own methods, not to main()
.
Upvotes: 0