![]() |
![]() |
![]() |
![]() |
![]() |
|
Now suppose that you want information about a box object's
dimensions to be accessible to member functions defined in the
box_car class, but you do not want that information to be generally
accessible, and you do not want functions defined outside the
box class to be able to change any of those dimensions.
You need to combine the virtues of private and public placement. First,
you return the dimension member variables to the private part of the
box class definition, to prevent accidental writing by member
functions defined in the box_car class definition. Second, you
provide access to the dimension member-variable values through readers
defined in the protected part of the box class definition:
class box {
public:
// Default constructor:
box ( ) { }
// Argument-bearing constructor:
box (double h, double w, double l) {
height = h; width = w; length = l;
}
// Volume member function:
double volume ( ) {return height * width * length;}
protected:
// Define readers:
double read_height ( ) {return height;}
double read_width ( ) {return width;}
double read_length ( ) {return length;}
private: double height, width, length;
};
Because the member variables are in the private part of the box
class definition, they are accessible only to member functions
defined in the box class. Because the readers are in the
protected part of the box class definition, they are accessible
only to member functions defined in either the box or
box_car class definitions.