Home Segments Index Top Previous Next

525: Mainline

The most extreme way to limit access to member variables and member functions at the point where they are inherited is to use private derivation.

When you make a derivation private, each public and protected member variable or member function in the base class acts as though it were part of the private part of the definition of the derived class.

Suppose, for example, that you derive the box_car class from the box class privately:

class box {
  public: double height, width, length;
    // 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;}
};
class box_car : public railroad_car, private box {  
  public: 
    // Default constructor: 
    box_car ( ) : box (10.5, 9.5, 40.0) { } 
    // Displayers: 
    virtual void display_height ( ) {cout << height;} 
    virtual void display_short_name ( ) {cout << "box";} 
    virtual void display_capacity ( ) {cout << volume ( );} 
}; 

Because the derivation of box_car, relative to the box classes, is a private derivation, all public and protected member variables and member functions defined in the box base class act as though they were private member variables and member functions of the derived box_car class. Because they act as though they were private, they are still accessible, but only to member functions defined in the box_car class, and not to member functions defined in any subclasses that may be derived from the box_car class. The display_height function, for example, can read from the height member variable.