jkuhn@walt.cc.utexas.edu (Jeff Kuhn) (03/02/90)
Here is an interresting problem that I did not have to worry about until an upgrade from 1.7 to 2.0. I need to access the protected members of a base class within a method of a derived class THROUGH a pointer to an object of the base class. Consider the following bit of code: class Base { //... protected: //... int i; }; class Derived : public Base { //... public: //... int getMember (Base *); }; int Derived::getMember (Base *bp) { return bp->i; // illegal: access through Base pointer not allowed } I believe that this could be done in 1.7, but 2.0 "fixed" the problem. There are two solutions that I have come up with. 1) Declare Derived a friend of Base: This works, but any classes derived from Derived must be declared friends also. 2) cast the Base pointer to a Derived pointer and resolve the scope of the member, i: return ((Derived *)bp)->Base::i; This works, but is a hack. Suppose that instead of i, a virtual function was desired. If bp was actually a pointer to an object of class Derived, would the correct virtual function be called? (Base::f() or Derived::f()) I need to be able to do this correctly in order to have class Derived handle a list of Base classes. Derived needs to be able to pass messages to objects in the list, regardless of whether they are of class Base or Derived. Any comments/suggestions would be appreciated. Jeff R. Kuhn jkuhn@ccwf.cc.utexas.edu