C++/access specifier
Expert: Zlatko - 12/3/2010
QuestionHello,
When a sub-class is deriving from a base-class, what does the access specifier imply?
eg. I have a Base class and a Child class as follows, if I use private or protected when Child derives from Base class, i,j,k will not be accessible from within main function, could you please explain? Regards
class Base {
int i;
protected:
int j;
public:
int k;
};
class Child: public Base {
};
int main() {
Child c1;
c1.i = 1;
c1.j = 2;
c1.k = 3;
}
AnswerHi lzzzz
In your example, Base::i is not accessible from main because it is not public in Base. The Base::j is not accessible from main for the same reason. The Base::k IS accessible from main, because it is public.
A derived class can access public and protected members of its base class. From within Child, the Base::j would also be accessible because protected members are available to derived classes.
Best regards
Zlatko