In this answer I'll assume that you used public
inheritance in your code (which was missing from the question).
[C++11: 11.2/1]:
If a class is declared to be a base class (Clause 10) for another class using the public
access specifier, the public
members of the base class are accessible as public
members of the derived class and protected
members of the base class are accessible as protected
members of the derived class. If a class is declared to be a base class for another class using the protected
access specifier, the public
and protected
members of the base class are accessible as protected
members of the derived class. If a class is declared to be a base class for another class using the private
access specifier, the public and protected
members of the base class are accessible as private
members of the derived class.
This covers the case where you're accessing a member of the same object.
However, it's a little curiosity of protected
member access that in order to access a protected
member of another object, it has to be located within the definition of the same type or a more derived type; in your case, it is in a less-derived type (i.e. a base):
[C++11: 11.4/1]:
An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C
. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C
or a class derived from C
. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C
or a class derived from C
.
That is, you'd have to run this code from within a Class1
member function.
Bjarne mentions this in his book The C++ Programming Language (Sp. Ed.) on page 404:
A derived class can access a base class' protected members only for objects of its own type [...] This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes.