Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can friend class have access to Base class private data through Derived class

Tags:

c++

friend

This is my first time to post a question here.

class Base {
     private:
         int base;
     friend class Question;
};

class Derived : public Base{
    private:
        int super;
};

class Question{
    public:
        void test(Base& base, Derived & derived)
        {
           int value1 =base.base;  // No problem, because Question is a friend class of base
           int value2 =derived.super; // Compile error, because Question is not a friend class of base
           // Question is here
           int value3 =derived.base;  // No Compile error here, but I do not understand why.
        } 
};

The question is indicated in the last row of Class Question.

like image 250
Zhongkun Ma Avatar asked Nov 01 '22 16:11

Zhongkun Ma


1 Answers

friend applies to all of the members of that type, whether or not the type is inherited. To stress this point: it is the members that are shared.

This means that your Question class has access to all members of Base, which is just int Base::base. Whether it accesses this member through an instance of Derived is irrelevant, because the actual member being accessed was declared on Base.

like image 171
cdhowie Avatar answered Nov 15 '22 05:11

cdhowie