Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

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 above example, 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 itself 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.

protected

The last access specifier is protected. protected acts just like private, with one exception that we can’t really talk about right now: “Inherited” structures (which cannot access private members) are granted access to protected members. But inheritance won’t be introduced until Chapter XX, so this doesn’t have any meaning to you. For the current purposes, consider protected to be just like private; it will be clarified when inheritance is introduced.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]