Home Segments Index Top Previous Next

738: Mainline

Note, then, that part of the work done by add is actually done by the two-argument constructor for the link class:

class link {
  public:
    link *next_link_pointer;
    railroad_car *element_pointer;
    link (railroad_car *e, link *l) {  
      element_pointer = e;             
      next_link_pointer = l;           
    }                                  
}; 

The link constructor is called when a new link object is created inside of the add member function:

class header { 
  public:   
    link *first_link_pointer; 
    header ( ) { 
      first_link_pointer = NULL; 
    } 
    void add (railroad_car *new_element) {                             
      first_link_pointer = new link (new_element, first_link_pointer); 
      ...                                                              
    }                                                                  
    ... 
}; 

Note that the add member function arranges for the value of the first_link_pointer variable to be the address of the new link object. Thus, add reroutes the pointer in the header object to point to the new link:

New                 | Old 
                    |           *-------* A header object 
                    |           |       | 
                    |           *-------* 
                    |           |       | 
                    |           *-------* 
                    |               | 
  Pointer rerouted  |               | 
    *-------------------------------* 
    |               |                         
    v               | 
*-------*           |           *-------*       *-------*  link 
|       | --------------------> |       | ----> |   0   |  objects 
|-------|           |           |-------|       |-------| 
|       |           |           |       |       |       | 
*-------*           |           *-------*       *-------* 
    |               |               |               |       
    v               |               v               v       
*-------*           |           *-------*       *-------*  railroad_car 
|       |           |           |       |       |       |  objects 
|-------|           |           |-------|       |-------| 
|       |           |           |       |       |       | 
|-------|           |           |-------|       |-------| 
|       |           |           |       |       |       |