// Purpose: Main program for testing Vehicle class hierarchy // Author: Dr Keith A. Shomper // Date: 17 Mar 2006 #include #include #include #include #include "vehicle.h" #include "car.h" #include "truck.h" #include "sports_car.h" using namespace std; typedef vector vectorOfVehicles; // prompt the user for the Vehicle type to create, and get the reply string prompt(void); int main() { vectorOfVehicles v; // allows dynamic creation of Vehicles // or objects derived from Vehicles int numVehicles = 0; // denotes how many Vehicles we have string reply; // indicates the type of Vehicle to build bool error = false; // set when a user response is in error // push a Vehicle into the vector so first "real" Vehicle is at position 1 v.push_back(new Vehicle("none")); // get the type of Vehicle to create reply = prompt(); while (reply != "quit") { // create the new Vehicle object and push it into the vector switch (reply[0]) { case 't' : case 'T' : v.push_back(new Truck); break; case 'c' : case 'C' : v.push_back(new Car); break; case 's' : case 'S' : v.push_back(new SportsCar); break; case 'q' : case 'Q' : reply = "quit"; continue; default : cerr << "Incorrect response\n\n"; error = true; } // if no error, then we have a new Vehicle to initialize via read() if (!error) { numVehicles++; v[numVehicles]->read(); } // reset error flag, and request a new Vehicle type error = false; reply = prompt(); } // report on what Vehicles were created to test read() and print() cout << "\nThe vehicles you created are:\n"; for (int i = 0; i <= numVehicles; i++) { // print the Vehicle characteristics (attributes) v[i]->print(); // use runtime type information (RTTI) to single out one type of // Vehicle, also allows us to test both inherited and non-inherited // accessor functions if (typeid(*v[i])==typeid(SportsCar)) { SportsCar *sc = (SportsCar *) v[i]; cout << "\t\tAt " << sc->getAcceleration() << " ft/sec^2, the " << sc->getName() << " can go from 0 to 60 mph in \n\t\t" << 60.0 / (sc->getAcceleration() * 3600.0 / 5280.0) << " seconds.\n"; } } return 0; } // prompt the user for the Vehicle type to create, and get the reply string prompt() { string reply; // the user reponse to the prompt string dummy; // to throw away "car" in the response "sports car" // prompt for and get user response cout << "\nWhich type of vehicle would you like to initialize" << "\n--car, truck, or sports car (or \"quit\" to exit): "; cin >> reply; // handle "sports car" as a special case if (reply[0] == 's' || reply[0] == 'S') { cin >> dummy; } return reply; }