// ptr15.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program finds the car with the shortest model name. // It is the correct version of ptr14.cpp. #include "ptr13.h" car::car(int doors, int cyl) { num_doors = doors; num_cyl = cyl; } char* car::GetModel() { return car_model; } void car::SetModel(char* mdl) { car_model = mdl; } void car::SetColor( avail_colors col) { car_color = col; } char* car::GetColor() { switch (car_color) { case white: return "white"; case black: return "black"; case green: return "green"; case red: return "red"; } return "Unknown"; } int car::GetNumCyl() { return num_cyl; } void car::SetNumCyl(int nc) { num_cyl = nc; } int main() { car *car_ptr = new car[3], *tmp_ptr; // Declare 3 car objects // Intialization.. done manually here. tmp_ptr = car_ptr; car_ptr -> SetModel( "BMW" ); car_ptr -> SetColor( green ); car_ptr++; car_ptr -> SetModel( "VW" ); car_ptr -> SetColor(); car_ptr++; car_ptr -> SetModel( "BENZ" ); car_ptr -> SetColor( black ); car_ptr = tmp_ptr; // Set it back to its initial place. // Find the car with the shortest model name. // Watch the use of "tmp_ptr". Also, find whether we are keeping track of original // position of car_ptr any more. // Assume the first car has the shortest model name // This is the object that is pointed by for (int i = 1; i < 3 ; i++) { tmp_ptr++; if ( strlen(tmp_ptr -> GetModel()) < strlen(car_ptr -> GetModel()) ) { car_ptr = tmp_ptr; } } cout << " The shortest model name for all the existing car objects is: " << car_ptr -> GetModel() << "\n"; return 0; } // The following is the result of compilation // Compilation successful // The following is the result of running the program. /* The shortest model name for all the existing car objects is: VW */