from C++ primer 5th edition:
have a look at these classes:
class Base {
friend class Pal;
public:
void pub_mem();
protected:
int prot_mem;
private:
int priv_mem;
};
class Sneaky : public Base {
private:
int j;
};
class Pal {
public:
int f1(Base b){
return b.prot_mem; //OK, Pal is friend class
}
int f2(Sneaky s){
return s.j; //error: Pal not friend, j is private
}
int f3(Sneaky s){
return s.prot_mem; //ok Pal is friend
}
}
Here Pal is a friend class of Base, while Sneaky inherits from Base and is used in Pal.
Now the very last line where s.prot_mem
is invoked, author gives the reason it works because Pal is a friend class of Base. But what i read so far, my understanding tells me that it should work anywawy, because s derives from Base and prot_mem is protected member of Base Class, which should have already access to Sneaky, can you explain why i am wrong or some more elaboration please?
No, protected variable
prot_mem
can only be accessed by derived class member, but not by third party class member, likeclass Pal
, ifPal
is not a friend ofBase
.