Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!ut-emx!walt.cc.utexas.edu!jkuhn From: jkuhn@walt.cc.utexas.edu (Jeff Kuhn) Newsgroups: comp.lang.c++ Subject: Re: Derived can't access protected members of base's Message-ID: <26464@ut-emx.UUCP> Date: 20 Mar 90 03:04:20 GMT References: <56.UUL1.3#5109@pantor.UUCP> Sender: news@ut-emx.UUCP Reply-To: jkuhn@walt.cc.utexas.edu (Jeff Kuhn) Organization: The University of Texas at Austin, Austin, Texas Lines: 54 In article <56.UUL1.3#5109@pantor.UUCP> richard@pantor.UUCP (Richard Sargent) writes: >We just got bitten by a 2.0 "gotcha". I wonder if anyone "in the know" >can explain the reasons for the restriction, and whether there is >some one who can provide an explanation for doing what we are trying >to do. > >C++ 2.0 very clearly states (acc.to Lippman) that "The derived class >has no special access privilege to objects of its base class. Rather, >the derived class has access privilege to the nonprivate inherited >members of a derived class object." (See Lippman, page 314 and 316) > >This either was not the case in 1.2, or the compiler was more lax >in regard to this rule. The Zortech 2.0 version doesn't seem to catch the error, but the Intek 2.0 compiler and (I believe) the AT&T compiler's won't let you access base member of another object from within a derived class. >The way we see the situation, we have to disagree with the restriction. >However, I am not foolish enough to think that BS does not have good >reasons for doing so. I sure would like to understand, 'though. I disagree too. >To our mind, we have a class derivation tree (root class and a number >of derived branches). We think that any object of a type from that >tree of classes should be able to access the protected members of >other objects also of that tree, but no class not in the tree. > >Assume we have an array of objects from that tree (or pointers to, >it makes no real difference). We wish to traverse the array and >access a protected member from each object (for whatever reason). >It seems we should be able to use a "base*" pointer, and just >access the item. So how can we accomplish this? > >Making the member public makes it too public :-). The only way that I have found to get around this is to typecast your base class pointer to a pointer to the derived class you want access through. This is not the safest solution. example: derived::f() { base *pb; ((derived *)pb)->member; } -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Jeff R. Kuhn jkuhn@ccwf.cc.utexas.edu Nth Graphics Austin, Texas