horstman@mathcs.sjsu.edu (Cay Horstmann) (04/01/91)
This is for language lawyers... Below you will find a base class B with a protected member b, a derived class D which declares classes PD, PD1 as friends. With Borland C++ (2.0), PD member functions can access b. I think this is as it should be. As I read it, declaring a class PD as a friend of class D means that all member functions of class PD are friends of D and friend functions of D have the same access rights as member functions of D. Since member functions of D can access protected members of B, so should friend functions of D. Is this interpretation correct? Does it reflect the reality in 2.0 compilers? If so, why does the second example below, with the class PD1, not compile? If this is a Borland bug, I guess I ought to mail it to them. Can anyone remember the recently posted internet address for this purpose? Thanx, Cay ------------------------------------------------------------------------------ #include <iostream.h> class B { protected: int b; friend class PB; public: B( int n ) { b = n; } void print() { cout << b; } }; class D : public B { int d; friend class PD; friend class PD2; public: D( int m, int n ) : d( m ), B( n ) {} void print() { cout << d << " " << b; } }; class PD { D* pd; public: PD( D* p ) : pd( p ) {} void print() { if( pd ) cout << pd->d << " " << pd->b ; } }; // ok, this shows that the friend PD of D can access the protected inherited b class PB { protected: B* pb; public: PB( B* p ) : pb( p ) {} void print() { if( pb ) cout << pb->b ; } }; class PD2 : public PB { PD2( D* p ) : PB( p ) {} void print() { if( pb ) cout << ((D*)pb)->d << " " << pb->b ; } }; // Error message: B::b is not accessible in function PD2::print() // Why can the friend PD2 of D can not access the protected inherited b ?
schweitz@lexvmc.vnet.ibm.com ("Eric Schweitz") (04/03/91)
Cay Horstman writes: | class B | { | friend class PB; | }; | class PB | { | protected: | B* pb; | //... | }; | class PD2 : public PB | { | void print() { if (pb) cout << ((D*)pb)->d << " " << pb->b; } | }; | | why does the second example below, ... , not compile? PD2 is derived from PB in your example, so PD2 has access to all of the members of PB. PB is a friend of B so it has access to all the members of B. ``Friendship'' is not inherited, so PD2 does NOT have access to the members of B through PB. I hope this answers the question. Also note that in your example, PD2 can actually access members of B via the class D. PD2 is a friend of D which is derived (publicly) from B. So, if you wrote PD2::print() as: void PD2::print() { if (pb) ((D*) pb)->print(); } it should compile. (I'm assuming pb points to the B part of a D, as you showed.) Eric. -=- Standard Disclaimer Here -=-. Eric Schweitz Lexmark International