MFC Programmer's SourceBook : Thinking in C++
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 {O}
// Public is just like C 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() {}  ///:~ 

The private keyword, on the other hand, means 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 user; 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, 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 have access to protected members, but not private members. But inheritance won’t be introduced until Chapter 12, 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


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru