class Parent {
protectedint foo;
}
class Child1 extends Parent {}
class Child2 extends Parent {
public Child2(Child1 other) {
foo = other.foo;
}
}
It can be rewritten in C++ like this:
1 2 3 4 5 6 7 8 9 10 11 12 13
class Parent {
protected:
int foo;
};
class Child1 : public Parent {};
class Child2 : public Parent {
public:
Child2(Child1 &other) {
foo = other.foo;
}
};
However, the C++ version will not compile. g++ gives:
1 2 3
parent.cpp: In constructor ‘Child2::Child2(Child1&)’:
parent.cpp:3: error: ‘int Parent::foo’ is protected
parent.cpp:11: error: within this context
Obviously the inheritance rules of protected members are different. Can anyone suggest how I should rewrite the C++ version to match the Java program? Thanks.
it's an error because Child2 isn't accessing its parent, it's accessing Child1's parent.
That seems to be the case, the way Java seems to do that is pretty stupid IMO, that's not what protected members are for. That seems more akin to friend classes tbqh.
EDIT: According to the Java spec, the protected keyword gives package wide access to any class in that package. If you create another class outside of that package (even one that extends class Parent), access is denied.
Notice that Child3 doesn't extend Parent, but can still access protected members.
1. This completely bastardizes the protected keyword, this is not what it should be used for.
2. This is why I think the idea of packages in languages like Java and Ada is stupid.