Domanda

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;
    }
};
È stato utile?

Soluzione 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.

Altri suggerimenti

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___|
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top