|
C++ access control
C++ introduces three new keywords to set
the boundaries in a structure: public, private, and
protected. Their use and meaning are remarkably straightforward. These
access specifiers
are used
only in a structure declaration, and they change the boundary for all the
declarations that follow them. Whenever you use an access specifier, it must be
followed by a colon.
public
means all member declarations that follow are available
to everyone. public members are like struct members. For example,
the following struct declarations are identical:
//: C05:Public.cpp
// Public is just like C's struct
struct A {
int i;
char j;
float f;
void func();
};
void A::func() {}
struct B {
public:
int i;
char j;
float f;
void func();
};
void B::func() {}
int main() {
A a; B b;
a.i = b.i = 1;
a.j = b.j = 'c';
a.f = b.f = 3.14159;
a.func();
b.func();
} ///:~
The
private keyword, on the
other hand, means that no one can access that member except you, the creator of
the type, inside function members of that type. private is a brick wall
between you and the client programmer; if someone tries to access a
private member, they’ll get a compile-time error. In struct
B in the example above, you may want to make portions of the representation
(that is, the data members) hidden, accessible only to you:
//: C05:Private.cpp
// Setting the boundary
struct B {
private:
char j;
float f;
public:
int i;
void func();
};
void B::func() {
i = 0;
j = '0';
f = 0.0;
};
int main() {
B b;
b.i = 1; // OK, public
//! b.j = '1'; // Illegal, private
//! b.f = 1.0; // Illegal, private
} ///:~
Although func( ) can access
any member of B (because func( ) is a member of B,
thus automatically granting it permission), an ordinary global function like
main( ) cannot. Of course, neither can member functions of other
structures. Only the functions that are clearly stated in the structure
declaration (the “contract”) can have access to private
members.
There is no required order for access
specifiers,
and they may appear more than once. They affect all the members declared after
them and before the next access
specifier.
|
|