Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: access to protected members Message-ID: <9630@alice.UUCP> Date: 18 Jul 89 00:05:22 GMT References: Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 57 In article , masotti@usc.edu (Glauco Masotti) writes: > I had some problems using protected members. I was pretty confident, after > reading the "evolution paper" from Bjarne, that my files would compile, but I > received instead complains from the compiler. Rather than jumping into your example right away, let's look at a simpler one. class X { protected: int x; }; The idea of `protected' is to nominate parts of a class that may only be used as scaffolding on which to build derived classes. Thus, for example, the following is legal: class Y: public X { public: void zot() { x = 0; } }; because, although Y::zot() appears to be clobbering X::x, in fact it does so only in its capacity as a part of a Y. For instance, suppose we change the definition of Y: class Y: public X { public: void zot() { x = 0; } void clear(X& xr) { xr.x = 0; } }; We then get a message that Y::clear() cannot access X::x, because xr.x is a member of a plain old X, not an X that's known to be part of a Y. Although this treatment seems counterintuitive at first, there are several reasons for it. First, if C++ did not restrict things this way, anyone could circumvent protection for any protected member of any object merely by deriving a dummy class as shown above. Second, it is quite easy to make things less restrictive if that's what you want: in this example, for instance, you could make Y a friend of X or make X::x public. It is much harder to make things more restrictive. Most of us who have grappled with this problem have found that there's often a way of doing what we want without running afoul of the protection restrictions. The solution, once found, may well be cleaner than the original version. Try it and see. -- --Andrew Koenig ark@europa.att.com