The purpose of this lab is to practice the concepts of abstraction, encapsulation, and data hiding (OOP). For this lab you will analyze and understand the given ADT interface functions on how to use them, and complete the given menu based programing for each case. The ADT will be a box in which a box can contain 1 item. The public operations for a box is to add an item to the box, remove the item from the box, and display the box.
If you did not finish during lab session, submit to your
depository directory before midnight:
/2020_S19/wk2/lab2.cpp
#include<iostream> #include<cstring> #include<cstdlib> using namespace std; #define MAX 64 // max cstring item length //Box//////////////////////////////////// class Box { private: char item[MAX]; int count; bool isEmpty(); public: Box(); Box(const char*); ~Box(); bool addItem(const char*); bool removeItem(); void display(); }; //MAIN/////////////////////////////////// int main() { int choice; char item[MAX]; Box *box = nullptr; do{ cout << "1. Create Box\n" << "2. Add item to Box\n" << "3. Remove item from Box\n" << "4. Display Box\n" << "5. Destroy Box\n" << "0. Exit\n" << "Enter choice: "; cin >> choice; cout << endl; switch(choice) { case 1: // create box if(box==nullptr) { try{ box = new Box; }catch(bad_alloc) { cout << "Bad allocation\n" << "Exiting Program\n"; exit(EXIT_FAILURE); } cout << "Box has been created\n\n"; }else { cout << "Box has already been created\n\n"; } break; case 2: // add item case 3: // remove item case 4: // display box case 5: // deallocate box case 0: // exit default:// invalid option } }while(choice!=0); //always check and deallocate memory if(box!=nullptr) { cout << "Deallocating...\n"; delete box; box=nullptr; } return(0); } ///////////////////////////////////////// Box::Box() { strcpy(this->item,""); this->count=0; } Box::Box(const char* itm) { strcpy(this->item, itm); this->count=1; } Box::~Box() { strcpy(this->item,""); this->count=0; } bool Box::addItem(const char* itm){ if(this->isEmpty()){ strcpy(this->item, itm); this->count=1; return(true); } return(false); // box is full, can't add } bool Box::removeItem() { if(!this->isEmpty()) { // box is full strcpy(this->item, ""); this->count = 0; return(true); } return(false); // box is empty, can't remove } void Box::display() { if(this->isEmpty()){ cout << "Box is empty\n" << "+---+\n" << "| |\n" << "+---+\n\n"; }else { cout << "Box is full\n" << "+---+\n" << "| # |\n" << "+---+\n" << this->item << "\n\n"; } } bool Box::isEmpty() { return(this->count==0); } /////////////////////////////////////////