#include #include #include struct person { string fname, lname; // object's variables are MEMBERS. int ssn, bd; // object's functions are called METHODS void print() { cout << fname << " " << lname << ", SSN=" << ssn << ", born " << bd << "\n"; } person(int s, string f, string l, int b) { ssn = s; fname = f; lname = l; bd = b; } }; struct database { protected: person * * data; int size, nextfreeslot; public: database() { size = 100; nextfreeslot = 0; data = new person * [size]; } ~database(); // destrcutor. always called automatically // when something ceases to exist. protected: void makeitgrow(); public: void insert(person *); // put it in next free place for me person * findoldest(); void put(int pos, person * ptr); // check pos is valid person * get(int pos); // also checks }; void database::makeitgrow() { int newsize = size+100; person * * newa = new person * [newsize]; for (int i=0; i=nextfreeslot) { cout << "Error in get\n"; return NULL; } return data[pos]; } void database::put(int pos, person * ptr) // check pos is valid { if (pos<0 || pos>nextfreeslot) { cout << "Error in put\n"; return; } if (pos==nextfreeslot) nextfreeslot += 1; if (ptr->fname == "Cornelius") { cout << "Cornelius is being violated!!!\n"; abort(); } if (pos>=size) makeitgrow(); data[pos] = ptr; } database::~database() { for (int i=0; ibd, oldestpos = 0; for (int i=1; ibd < oldest) { oldest = data[i]->bd; oldestpos = i; } return data[oldestpos]; } database read_data() { ifstream in("/home/www/class/een118/labs/database10.txt"); if (in.fail()) { cerr << "No file\n"; exit(1); } database newdb; while (true) { int a, b; string c, d; in >> a >> c >> d >> b; // The file contains ssn fname lname bd if (in.fail()) break; newdb.insert(new person(a, c, d, b)); } in.close(); return newdb; } void short_simple_task() { int i; database DB = read_data(); person * x = DB.findoldest(); x->print(); cout << "Change his name...\n"; x->fname = "Old Man"; x->print(); int a = 2+2; // Now I can't do something stupid like // DB.data[i] = DB.data[i+100000000] // I have to say this instead DB.put(i, DB.get(i+100000000)); // and that gets safely caught. person * y = DB.findoldest(); y->print(); // No memory leak here now, the destructor ensures that // the database and all the people are recycled. } void main() { /* Big program doing a lot of stuff */ short_simple_task(); /* many many more things happen now */ }