In this topic, the standard state of C ++ 03 (my attention):
11.5 Access to protected member
1 When a friend or member function of a derived class refers to a protected non-static member function or a protected non-static data element of the base class, access control is applied in addition to those described earlier in clause 11. Except in cases where a pointer to the element is generated (5.3.1 ), access should be through a pointer to a link, a link to an object or a class object (or any class derived from this class) (5.2.5).
What you are doing here is trying to access through a pointer to a base class, which is illegal. If you change the signature to
int func(B* p)
You will find that it now compiles normally.
This is also the reason that you can access a from within class B without any problems: access is via the implicit this pointer, which is of type B* (derived class again). If you tried this:
A* parent = static_cast<A*>(this); int x = parent->a;
You will find that it will not compile for the same reason.
The opposite also applies: if you omit the pointer p to B* , you can access the protected element simply:
class A { public:
source share