I'm receiving a compiler error from the following code. In OuterB::InnerB::foo, the compiler allows access to this->i but prohibits access to other.i though (from my perhaps mis-informed understanding) access should be granted in both cases -- isn't that what "protected" is for?
class OuterA {
public:
class InnerA {
protected:
int i;
public:
void foo( InnerA& that ) {
this->i - 1; // no issue here
that.i - 1;
}
};
};
class OuterB : public OuterA {
public:
class InnerB : public OuterA::InnerA {
public:
void foo( OuterA::InnerA& that ) {
this->i + 1; // access to protected member OK
that.i + 1; // access not OK, doesn't compile
}
};
};
int main( int argc, char** argv ) { return 0; }
The error:
1 2 3
innerClassVisibilityIssue.cpp: In member function 'void OuterB::InnerB::foo(OuterA::InnerA&)':
innerClassVisibilityIssue.cpp:5: error: 'int OuterA::InnerA::i' is protected
innerClassVisibilityIssue.cpp:21: error: within this context
Well, the error says the problem. You can't do that.
foo() can modify any public or protected part of OuterA::InnerA that is part of *this. "that" is not part of *this, and therefore you can only see the public part.
Hmph. I guess C++ just isn't behaving the way I had hoped.
It seems logical for objects with a common base class to have direct access to that base class' public and protected members. I believe that such a thing is possible in Java, and I had hoped the idea would be applicable here too.
Well we could get into discussions about whether protected data is a good idea in the first place but I won't start it because the C++ community is very divided over the issue. The purpose of the protected section is not to give completely different objects access to each others internal parts. I and some other people feel that protected data violates encapsulation anyway but to allow completely different objects access to each other's inner parts simply because they happen to be of the same type would open up a huge can of worms (major security problems) in my mind. I'm very thankful that C++ doesn't allow that (no pun intended). Then again, if C++ had disallowed protected data, people would just make protected/public mutator functions. The existence of the protected region of a class exists for valid purposes but it can be misused easily just like any other tool of the language.
By the way, that example didn't have to use nested classes to prove the point. The use of nested classes just convuluted the question.