TITLE: Friends, derived classes, and limited access rights PROBLEM: news@bbn.com (News system owner ID) I'm running into a restriction in the declaration of friend member functions. I'm developing a base class which is used by many derived classes. In one or two of those derived classes, I want to allow use of a "dangerous" member of the base class. e.g; class Base { private: friend void Derived::carefull(); // Error: void dangerous(); }; class Derived : public Base { public: void careful(); }; The problem is that class Base must be declared before class Derived but the friend declaration requires that Derived be declared first (a classic chicken or egg problem). RESPONSE: rmartin@rational.com (Robert C. Martin) The following demostrates an idiom which can be useful in cases like this. The idea is to define a nested Accessor class which provides friendship access to a restricted set of the private members of base. In this way you can allow certain derived classes to have access to certain private base member functions. -------------------------- CUT HERE -------------------------------- #include "iostream.h" class Base { public: Base() : itsAccessor(this) {} protected: class Accessor& getAccessor() const {return itsAccessor;} private: friend class Accessor; void dangerous() {cout << "boom" << endl;} class Accessor { friend class Base; friend class Derived; Accessor(Base* b) {itsBase = b;} void dangerous() {itsBase->dangerous();}; Base* itsBase; } itsAccessor; }; class Derived : public Base { public: void careful() {getAccessor().dangerous();} }; main() { Derived d; d.careful(); } ---------------------------------------------------------------------------- Those classes which should have special access to protected base members can be listed as friends of Accessor rather than friends of Base. The friends of Accessor will have access only to those functions defined in Accessor, thus their access to Base is carefully limited. Some care must be taken when using this idiom. The Accessor constructor must not depend upon the Base object being constructed! It is receiving the base pointer before the Base constructor body has been called!