TITLE: access protection, inheritance, and base class pointers (Newsgroups: comp.lang.c++.moderated, 4 Dec 97) LEROY: Jean-Louis Leroy > > consider the following illegal code: > > class B > { > protected: > void f(); > }; > > class D : public B > { > protected: > void g(B* p) > { > f(); // ok > p->f(); // error > } > }; > > > By the same token, wouldn't it be a better world if the code above did > compile? > WAN: Chichiang Wan FDIS 11.5 says "...the access must be through a pointer to, reference to, or object of the derived class itself..." (the full paragraph is attached below). However, that paragraph may not be a answer to your question which seems to be why there is such restriction. Let me try to give an answer. When I(someone) design a (non-static) protect data member (pdm), I am only giving permissions to derived classes (directly/indirectly, but drived properly) to modify THEIR copies of pdm, not pdm in instances of my designed class. Without the above restriction, there would be be a loophole: you could modify pdm in instances of my class without going through interface fucntions of my class by simply designing class derived from mine with a member function taking reference type of my class. Given that, it is easy to understand that the above restriction only applies to nonstatic data member. The above reasoning seems less obvious for non data members. However, access checking is uniformly for names. p.s. one of your alternative is to let D be friend of A, so permission is already given when you design A. That does not contradict to the following: 11.5 Protected member access [class.protected] 1 When a friend or a member function of a derived class references a protected nonstatic member of a base class, an access check applies in addition to those described earlier in clause _class.access_.4) Except when forming a pointer to member (_expr.unary.op_), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (_expr.ref_). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class). [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ] [ about comp.lang.c++.moderated. First time posters: do this! ]