Despite the fact that access control in C ++ works on the basis of each class (as opposed to the basis for each instance), the protected access specifier has some features.
The language specification wants to make sure that you are accessing the protected member of some base subobject belonging to a derived class. You should not have access to the protected members of some unrelated, independent base type objects. In particular, you cannot access protected members of autonomous objects of a basic type. Access to protected members of base objects that are embedded in derived objects as base subobjects is permitted only.
For this reason, you need to access protected members through the syntax pointer->member , reference.member or object.member , where the pointer / link / object refers to the derived class.
This means that in your example, the protected member somethingProtected() not available through Base objects, Base * or Base & pointers, but is available through Derived objects, Derived * and Derived & pointers Derived & references. Your simple access somethingProtected() allowed, as it is simply a shorthand for this->somethingProtected() , where this is of type Derived * .
b.somethingProtected() violates the above requirements.
Note that in accordance with the above rules in
void Derived::somethingDerived() { Base *b = this; b->somethingProtected();
the first call will also fail, and the second will be compiled, although both are trying to access the same object.
AnT May 28 '13 at 6:28 2013-05-28 06:28
source share