The encapsulated data in a class is accessible to the member functions of that class. Such access is allowed, of course, because the member functions and the data are parts of the same implementation: to be written, the writer of the code must know the details of the data. The data is, however, completely inaccessible to all non-member functions.
The Location class is used to illustrate the syntax and placement of the the data and the code for a class. The complete definition, including the implementation, for the Location class is given below.
class Location { // Version 1
private:
int currentX, currentY;
public:
Location(int x, int y); // specific location
Location(); // default location
int Xcoord(); // return x-axis coordinate
int Ycoord(); // return y-axis coordinate
};
// the implementation follows
Location::Location( int x, int y ) { currentX = x; currentY = y; }
Location::Location () { currentX = -1; currentY = -1; }
int Location::Xcoord() { return currentX; }
int Location::Ycoord() { return currentY; }
Notice that the data is placed in the private portion of the class definition. It is
natural to wonder why, if the data is hidden, it is textually visible in
the class definition. Why not make the data hidden both conceptually and visually.
The placement of the data in the class definition is a compromise in the design
of the overall system software. This compromise simplifies the job of the compiler
and linker at the expense of exposing to view (but not to access) the variables
declared in the private section of the class definition.
The general syntax of the implementation of a member function is as follows:
ReturnType ClassName::memberFunctionName ( ArgumentList ) { Statements }
where
|
|
Last updated: July 24, 1995 / kafura@cs.vt.edu