Introduction to Programming and C++

Contents Previous Topic Next Topic

The visibility of a class member variable or member function determines from where that variable can be accessed/modified or from where the member function can be called.

There are three classifications of visibility:

public:
The member variable/function can be accessed/called in any statement within any function.
protected:
The member variable/function can only be accessed/called in the statements of functions of the class to which the variables/functions belong and any derived classes (subclasses).
private:
The member variable/function can only be accessed/called in the statements of member functions of the class to which the variables/functions belong.

Visibility is implemented through labels and all member variables or member functions which appear after a visibility label have that visibility. For example, the standard grouping is to list all private members first, followed by all public members, as is demonstrated here:

class AClass {
	private:
		int n;
		double x, y;

	public:
		const int N;
		int f();
		int g( double, double );
};

It is possible to use multiple labels within a class declaration, however this can only obfuscate code.

Private versus Protected

In general, is is preferable to declare a member variable to be private as opposed to protected. Declaring a member variable to be protected breaks encapsulation, as now the restrictions on the possible values of that variable must be checked in multiple places. A modification at the top-level class may not be reflected in the operations on that variable in the derived classes.

Friends

It is possible to by-pass visibility using the modifier friend:

  • If a class is declared to be a friend of a class, then all the private members may be accessed/called by any member function of the class which is a friend, and
  • If a function is declared to be a friend of a class, then that function is able to access the private members of any any instance of that class which are used by that function.

The concepts of friends is discussed more thoroughly here.


Contents Previous Topic Top Next Topic