C++ Concept Map

Access control

Whereas scope is about the names declared and used in regions of program text between braces, access control is about the use of objects, and the functions that use them. Objects can control access to their internal state by use of the keywords private, public and protected. By default, all class members are private; they cannot be accessed externally (see the use of structures, and the use of the friend declaration for variations on this). Using the section keyword public makes any names declared in that section accessible from outside. e.g. in

class Access {
  int x1;
  void f1();
public:
  int x2;
  void f2();
};

x1 and f1 are private, but x2 and f2 are public. There can be any number of sections, private or public, in a class declaration. It is conventional to make explicit use of the keyword private, even though default access is private. Thus:

class Access {
private:
  int x1;
  void f1();
public:
  int x2;
  void f2();
};

is preferred over the previous declaration.

The keyword protected is used only when inheritance between classes needs to be controlled, and allows derived classes to access private members of a base class directly.


Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley