Is it possible to somehow provide access to protected class variables, child classes of a friend class?

Well, here is such an incident:

class foo { friend class bar; int i; public: void hello() { i = 0;/*OK*/ }; }; class bar { public: void hello(foo *f) { f->i = 0;/*OK*/ }; }; class baz : public bar { public: void hello(foo *f) { f->i = 0;/*ERROR*/ }; } 

Please, tell me how to solve this problem.
PS This kind of child classes will be about twenty

    2 answers 2

    It is impossible. Another class is only the class that is explicitly listed in the list of friends. Therefore, you have to either enumerate all classes explicitly, or add to bar functions that allow child classes to work with private members of foo .

    In any case, you should not abuse a friend , most likely you have a design problem, and the problem can be solved much simpler and more elegant without a friend at all.

    • "You should not abuse a friend," so I ask. But for the "add to bar functions" , thanks for the idea, helped out (s). - Vitya Nikolaev

    You need to provide access to private members of the class from the outside using get/set functions. Like that:

     class foo { private: int i; public: void set_i(int i) { this->i = i; } int get_i() const { return i; } public: void hello() { i = 0;/*OK*/ }; }; class bar { public: void hello(foo *f) { f->set_i(0);/*OK*/ }; }; class baz : public bar { public: void hello(foo *f) { f->set_i(0);/*OK*/ }; } 
    • one
      No, it does not work for me, in fact, this option also tried to use, but the protected members of the class are not available. And the people who are the first have already solved my problem (“add functions to the bar that will allow the child classes to work with private members of foo.”) - Viktor Nikolaev
    • There is no inheritance from foo , your code is non-working. - ixSci
    • Yes, after the answer, and he himself thought that the CU needed access to closed members from the outside, and not through heirs. The answer is corrected. - aleks.andr