TITLE: data accessors (Newsgroups: comp.lang.c++, 5 Aug 97) SEMENIUK: Andrzej Semeniuk (andrzej@generation.net) : Given a class A with data/method members {a,b,c} I want the member 'b' : to be accessed only by an object of a class of type B (B is not a : subclass of A). For any other object of class C (C not subclass of B or : A), it is prevented (by the compiler) from accessing 'b'. : : Are there any programming languages out there that allow such : modelling? KUEHL: kuehl@horn.informatik.uni-konstanz.de (Dietmar Kuehl) C++ is such a programming language, at least if some indirection is used (it is not immediately possible in C++). Using a variation on "Data Accessors" (see the article of Karsten Weihe and me in the July 1997 issue of the C++ Report for more information), it easily possible: template class SelectiveFriend { friend class Friend; static T &access(Str &str) { return str.*member; } static T const &access(Str const &str) { return str.*member; } static T &access(Str *str) { return str->*member; } static T const &access(Str const *str) { return str->*member; } }; This is basically an accessor object which can be used to grant access to an arbitrary member of an arbitrary class to some arbitrary class. This class is used like this: class B; class A { T1 a; T2 b; T3 c; public: typedef class SelectiveFriend b_access; friend b_access; // ... }; // .. then in some member of 'B': void B::foo(A const &a) { A::b_access::acess(a) = T2(); // write the member T2 b = A::b_access::access(a); // read the member } Unfortunately, this technique is not yet supported by many compilers... (KCC does compile code like this but other compilers I have available do not). However, every C++ compiler conforming to the standard will be able to compile this code. But in this case it is still possible to implement specific accessors for every class/member for which it is desired/necessary. Of course, the syntax used is not that straight forward as you suggested but then I think it is a feature only rarely needed: It creates strong coupling between two class ('A' and 'B') which indicates that both classes should be part of the same component anyway. Thus, it would be reasonable to grant 'B' access to all members of 'A': After all, you are implementing a component and only want to hide the internals of the components to the clients of this component. I guess that similar approach can be used in other languages, too.