This answer seems to suggest it should work so why does my example kick up a compiler error:
class Class1
{
protected:
long m_memberVar;
};
class SubClass1: public Class1
{
public:
void PrintMember(Class1 memberToPrintFrom)
{
Console::Write("{0}", memberToPrintFrom.m_memberVar); // <-- Compiler error: error C2248: 'BaseClassMemberAccess::Class1::m_memberVar' : cannot access protected member declared in class 'BaseClassMemberAccess::Class1'
}
};
[Edit] – changed subclass to a public inheritance on Need4Sleep’s suggestion but it makes no difference.
In this answer I’ll assume that you used
publicinheritance in your code (which was missing from the question).This covers the case where you’re accessing a member of the same object.
However, it’s a little curiosity of
protectedmember access that in order to access aprotectedmember 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):That is, you’d have to run this code from within a
Class1member function.Bjarne mentions this in his book The C++ Programming Language (Sp. Ed.) on page 404: