Understanding member access with inheritance / friend class in C++

113 views Asked by At

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?

3

There are 3 answers

1
lulyon On BEST ANSWER

my understanding tells me that it should work anyway, because s derives from Base and prot_mem is protected member of Base Class, which should have already access to Sneaky

No, protected variable prot_mem can only be accessed by derived class member, but not by third party class member, like class Pal, if Pal is not a friend of Base.

0
Daniel Daranas On

Without friendship, Pal only sees Sneaky or Base's public members. The fact that one member of Base is protected does not benefit Pal in any way - it only benefits Sneaky.

2
Angew is no longer proud of SO On

The thing is that while Sneaky can access prot_mem, the code you're showing is not in Sneaky, it's in Pal. If Pal was an unrelated class, it couldn't access prot_mem, which is also protected in Sneaky. However, Pal is a friend of Base, which gives it the access necessary.