You are here:

C++/access specifier

Advertisement


Question
Hello,

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;
}

Answer
Hi 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.