Home Segments Index Top Previous Next

213: Mainline

You prevent direct member-variable access by declaring the member variables in a separate, private part of the class definition—the one marked with the private: symbol.

You can, for example, redefine the tank_car class as follows, with the radius and length member variables moved from the public part of the class definition into a part marked by the private: symbol.

class tank_car {
  public:
    tank_car ( ) {radius = 3.5; length = 40.0;}
    tank_car (double r, double l) {radius = r; length = l;}
    double read_radius ( ) {return radius;}
    void write_radius (double r) {radius = r;}
    double read_diameter ( ) {return radius * 2.0;}
    void write_diameter (double d) {radius = d / 2.0;}
    double read_length ( ) {return length;}
    void write_length (double l) {length = l;}
    double volume ( ) {return pi * radius * radius * length;}
  private:                  
    double radius, length;  
}; 

With the tank_car class so redefined, future attempts to refer to a tank_car object's radius and length member-variable values via the class-member operator fail to compile.

t.radius      <-- Evaluation fails to compile; 
                  the radius member variable is in the 
                  private part of the class definition 
t.radius = 6  <-- Assignment fails to compile; 
                  the radius member variable is in the 
                  private part of the class definition