Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!magnus.acs.ohio-state.edu!tut.cis.ohio-state.edu!ucbvax!ulysses!ulysses.att.com!mwb From: mwb@ulysses.att.com (Michael W. Balk) Newsgroups: comp.lang.c++ Subject: Re: protected member functions Summary: Protected member access is restricted to derived objects, not contained objects Message-ID: <14474@ulysses.att.com> Date: 16 Mar 91 22:48:42 GMT References: <1991Mar14.215717.28199@asc.slb.com> Sender: netnews@ulysses.att.com Lines: 49 In article <1991Mar14.215717.28199@asc.slb.com>, wkd@asc.slb.com (Bill Duttweiler) writes: > > Is it illegal to call a protected member function on an instance other > than 'this'? Consider the following simple example: > > class A > { > public: > A(); > protected: > void SetState(); > }; > > class B : public A > { > public: > B(A* a) { MyA = a; } > void Foo() { MyA->SetState(); } > protected: > A *MyA; > }; The problem here is that MyA is a pointer to an instance of A -- it is *not* an instance of B. In otherwords, MyA->SetState() is not permitted regardless of whether Foo is a member function of class B or not. If this were not the case, then one could access the protected and private members of any object simply by deriving from that object's class. In order to access A::SetState from an instance of class B, class B should be modified as follows: class B : public A { public: B() {} void Foo() { SetState(); } }; Since B is derived from A it already contains everything that is in A through the derivation. In the above definition of class B, Foo executes a member function of the base part of the same object. This is legal since and instance of B is also an A. Michael W. Balk AT&T Bell Laboratories Murray Hill, NJ 07974 mwb@ulysses.att.com