In this answer, I 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 a base class (section 10) for another class using the public access specifier , members of the public base class are available as public members of the derived class and protected members of the base class are available as protected members of the derived class . If a class is declared a base class for another class using the protected access specifier, members of the base class public and protected are available as members of the protected derived class. If a class is declared a base class for another class using the private access specifier, public and protected members of the base class are available as private members of the derived class.
This applies when you are accessing a member of the same object.
However, a bit of the curiosity of protected member access, in order to access the protected element of another object, it must be located in a definition of the same type or a more derived type; in your case, it is in a less derived type (i.e. base):
[C++11: 11.4/1]: optional outside access control described in section 11 above applies when a non-static data member or non-static member function is a protected member of its naming class (11.2). As described above, access to a protected member is granted because the link is found in a friend or member of some class C If the access consists in forming a pointer to a member (5.3.1), the sub-name specifier should denote C or a class derived from C All other calls include an (possibly implicit) expression of the object (5.2.5). In this case, the class of the expression of the object must be C or a class derived from C
So you will need to run this code from a member function of Class1 .
Bjarne mentions this in his book The C ++ Programming Language (Sp. Ed.) On page 404:
A derived class can access protected members of the base class only for objects of its own type [...] This prevents subtle errors that would otherwise occur when one derived class distorted data belonging to other derived classes.
Lightness races in orbit
source share