[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Static members Up: Classes Previous: Friend classes and functions

Class member privacy

Class members can have 3 types of privacy
private
- can be used only by member functions and friends
protected
- like private except that derived classes have access to them too. Try not to use this - it can help performance but it breaks encapsulation.
public
- available to any function.
By default class members are private. You often want the data to be private (so that they can't be tampered with from the outside) but the functions public (so that they can be called by other objects). If you want other objects to be able to change the data, write a member function that the objects can call and make sure that the member function does validity checking. Then other member function that use the data won't have to check for validity first.

A private function is often called a helper or utility function because its for the benefit of other member functions. Note that a member function

1.
can access private data
2.
is in scope of class
3.
must be invoked on an object

If you have the choice of writing a friend or member function, choose a member function.

Note that structs are just classes which default to public members and public inheritance. By convention they're used (if at all) for data-only classes.


next up previous contents
Next: Static members Up: Classes Previous: Friend classes and functions
Tim Love
2001-07-05