문제

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;
    }
};
도움이 되었습니까?

해결책 2

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.

다른 팁

protected can be accessed only in hierarchy, but if you want exception, making friend is the way.

Friend class can access both private and protected members of the class.

b->f() and b->i are not accessing f and b of his own base, but of somebody else base (the one pointed by b)

sub    base
|____b_|___i___|
     |
     |_
       |
       V
sub    base
|____b_|___i___|
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top