c++ access level
class Base{
public:
void setX(int a) {x=a;}
private:
int x;
};
class D1: protected Base{};?
class D2: public D1{};
what is the access level for the membe开发者_开发百科r function setX() in the class D2 ? is it protected ? of private? Can any kind people explain this, I mean how to judge access level regarding inherence ....something like this. thank you!
Edited: Add on more question
but WHy I cannot call : d2.setX() ? d2 is a instance of D2. It turns out compiler error – user658213 0 secs ago edit
SetX is protected and x is inaccessible from D2. You can only restrict access, you cannot broaden it.
setX becomes protected via protected inheritance in D1, and remains protected through public inheritance in D2. Thus, its final access level in D2 is protected.
The reason you would not be able to call setX would depend on the calling context. If you are calling from outside of a class derived from Base or D1 (e.g. D2), then you wouldn't be able to call it for the same reason you can not call any protected members - they are only for use by derived classes.
精彩评论