// ptr19.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program fixes the memory leak problem of ptr18.cpp. What is the difference? #include "ptr18.h" car::car(int doors, int cyl) { num_doors = doors; num_cyl = cyl; car_model = new char[10]; } char* car::GetModel() { return car_model; } void car::SetModel1(char* mdl) { strcpy(car_model, mdl); } void car::SetModel2(const char* mdl) { strcpy(car_model, mdl); } void car::SetModel3(char* mdl) { strcpy(car_model, mdl); *car_model = 'X'; } 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"; } car::~car() { cout << "Destructing" << endl; delete [] car_model; } int main() { car car_arr[3]; // Declare 3 car objects char *m1 = new char[4], *m2 = new char[5]; strcpy(m1, "BMW"); strcpy(m2, "BENZ"); car_arr[0].SetModel1( m1 ); car_arr[0].SetColor( green ); car_arr[1].SetModel2( "VW" ); car_arr[1].SetColor(); // Notice the output of the following call car_arr[2].SetModel3( m2 ); car_arr[2].SetColor( black ); for (int i = 0; i < 3 ; i++) { cout << "The model of car # " << i+1 << " is: " << car_arr[i].GetModel() << "\n"; cout << " and its color is: " << car_arr[i].GetColor() << "\n"; } cout << endl << "m1 now is " << m1 << endl; cout << "m2 now is " << m2 << endl; delete [] m1; delete [] m2; return 0; } // The following is the result of compilation //Compilation successful // The following is the result of running the program /* The model of car # 1 is: BMW and its color is: green The model of car # 2 is: VW and its color is: white The model of car # 3 is: XENZ and its color is: black m1 now is BMW m2 now is BENZ Destructing Destructing Destructing */