The private and public labels in the class definition specify the visibility of the members that follow the labels. The mode invoked by a label continues until another label occurs or the class definition ends.
Private members can be accessed only by member functions. (They can also be accessed by friend classes and functions; friends are discussed in Chapter 6.) The private members define the internal workings of the class. They make up the class's “implementation.”
Public members can be accessed by member functions, and by any other functions in the program as long as an instance of the class is in scope. The public members determine how the class appears to the rest of the program. They make up the class's “interface.”
The Date class declares its three integer data members as private, which makes them visible only to functions within the class. If another function attempts to access one of these private data members, the compiler generates an error. For example, suppose you try to access the private data members of a Date object:
void main()
{
int i;
Date myDate( 3, 12, 1985 );
i = myDate.month; // Error: can't read private member
myDate.day = 1; // Error: can't modify private member
}
By contrast, the display function is public, which makes it visible to outside functions.
You can use the private and public labels as often as you want in a class definition, but most programmers group the private members together and the public members together. All class definitions begin with the private label as the default mode, but it improves readability to explicitly label all sections.
The Date class demonstrates a common C++ convention: its public interface consists entirely of functions. You can view or modify a private data value only by calling a public member function designed for that purpose. This convention is discussed further in the section “Accessing Data Members”.