Search code examples
c++friendprotected

Why need to be a friend to access protected members?


When I'm in Sub::f() and try to access the protected members of another sub-class to which the Base* b pointer points to, it won't compile until Sub is a friend of Base. Why do I need to do this?

class Base{
//friend class Sub;
protected:
    int i;
    virtual void f() = 0;
};

class Sub : public Base{
    Base* b;
public:
    Sub(Base* ba) : b(ba){}
    void f(){
        b->f();
        cout << b->i << endl;
    }
};

Solution

  • protected members are accessible in own class and in derived class but not outside of the class so if you want to do it, use 'friend'. And because of this feature provided by CPP,CPP is not 'fully or complete' object oriented programming language (loophole) as we can access private members too with friend's help.