How to make available the private field of a nested class only in the external class?

template <typename T> class A { public: class B { private: T* bar; public: //... }; void test(T data) { B foo(data); T* p = foo.bar; //нет доступа } }; 
  • to move class B from public to private, and make the field public? - VladD
  • @VladD, no, B should be public - defias

2 answers 2

You need to declare class A to be a friend of class B :

 template <typename T> class A { public: class B { friend class A; // A друг B private: T * bar; public: //... }; void test( T data ) { B foo( data ); T * p = foo.bar; // доступ есть } }; 

    In any case, you have a design problem, and the recommendations to plant a getter, or, even worse, arrange friendship classes, are very dangerous - read Golub (tip 117), it describes why - by making a friendly class, you will give your friend the full right to dig into all fields of parent-friend . Subversion of encapsulation is obvious.

    In short, the entire object-oriented design is needed to manage complexity by, in particular, encapsulation. And you are advised to break it.

    UPD: The answer to the question, in this case, is the phrase "you have a problem in design"

    • Some author's paranoid task, in practice, the easiest way is to make this public field and not to steam. - avp
    • Your record is not the answer to the question - Cerbo
    • @Cerbo let me disagree. The fact is that having friendly classes or creating a naive public method seriously violates encapsulation. Therefore, instead of sculpted crutches, the design should be revised. - gbg
    • @gbg: Your line of thought would be more understandable if you didn’t refer to Golub (by the way, who is this?), tip number 53465783, but formulate this advice yourself, with arguments, for those who haven’t yet read or understood. - VladD
    • Although yes, I also feel that a friend and the need for it is not a good design. But I can not justify (s). - VladD