Hi, based on a short amount of research, I've learned that the following code is illegal in C++
1 2 3 4 5 6 7 8 9
|
class Base {
protected:
int i;
};
class Derived : public Base {
int f(Base* b) { return b->i; } // <- illegal
int g(Derived* d) { return d->i; } // <-- works
};
|
What I don't understand here, is why a inside of Derived, you cannot access a protected member of Base from an instance of a Base, but you can from an instance of Derived. This seems counter to the ideas of OO, as all instances of any type of Base should be treatable as Bases, and anything in Base's interface (in this case, the protected interface which is accessable by Derived) should be accessable from any Base.
That said, I have two questions:
#1, why is this not allowed, when it is in other languages (at least Java)? The only thing I can really imagine is having a protected function used for something (like a Template Method), where an evildoing subclasser could make that function mean something else, but that's true for a lot of things in C++.
#2, is there any way to get around this without hacking (i.e., making "i" public-- even though it doesn't make sense to be in Base's public abstraction, or making Derived a friend of Base-- which wouldn't be scalable since you might not even have access to the base class's source down the road)?