Add a class destructor to delete dynamically allocated data

Assignment Help C/C++ Programming
Reference no: EM131479582

Programming Assignment: Inventory Class Hierarchy

This assignment builds on the class hierarchy of Lab (see below)

InventoryItem

-  description: string
-  qantityOnHand: int
-  price: double

+ InventoryItem()
+ InventoryItem(string, int, double)
+ getDescription() const: string
+ getQuantityOnhand() const: int
+ getPrice() const : double
+ setDescription(string): void
+ setQuantityOnhand(int): void
+ setPrice(double): void
+ display() const: void
+ read(ifstream&): void

                            129_Arrow.jpg

Book

- title: string
- author: string
- publisher: string

+ Book()
+ Book(string, int, double, string, string, string)
+ getTitle() const: string
+ getAuthor() const: string
+ getPublisher() const : string
+ setTitle(string): void
+ setAuthor(string): void
+ setPublisher(string): void
+ display() const: void
+ read(ifstream&): void

Task 1: List of authors

Our design so far assumes that a book has only one author. You need to modify class Book to be able to accommodate multiple authors, each represented with a name. A good way to do this is to use the C++ Standard Template Library and declare member authors to be of type vector<string>. However, since one of the objectives of this assignment is to practice with dynamic data and pointers as members of a class, we want to define a new class Listto store the list of author names.

List should have two private data members, a pointer to string which will be use to dynamically allocate an array of string of a certain size, integer representing the size of the allocate array (call it listCapacity), and integer representing the actual number of elements in the list (call it listSize). List should also have the following public member functions (at a minimum):

a) a parametrizedclass constructor to initialize the list to at least one item. Note that the constructor does not populate the list, it just allocates a string array of a given capacity. You should also provide a default constructor.

b) a functionsize() that returns the number of items in the list.

c) a function that returns the value in the ith element (be sure to validate i).

d) a function that adds a new item to the back of the list (call it push_back() ). If the list is full, allocate a new array of the appropriate size, copy all existing elements into the new array, and add the new item.

e) a function that removes the element at the back of the list (call it pop_back()).

f) a function clear() to delete all the items from the list.

Exercise 1. Define a class List with the above specification.

Task 2: Testing Class List

Consider the following test driver program:

#include"List.h"
voidtestList();
intmain()
{
tesList();
cin.get();
system("pause");
return 0;
}
//*******************************************************
// This function is used to test class List
inttestList()
{
List a(3); // testing constructor, push_back(), size(), and getItem()
a.push_back("James Bond");
a.push_back("Iman Tillman");
a.push_back("Mary Joe Hernandez");
a.push_back("Roger Moore"); // one more that original capacity
cout<<"Number of items in list a: "<<a.size()<<endl;
for (inti =0; i<a.size(); ++i)
cout<<a.getItem(i) <<endl;

cout<<endl<<"Testing List coping: "<<endl;
List b = a; // testing copy constructor
cout<<endl<<"list b: "<<endl;
for (inti =0; i<b.size(); ++i)
cout<<b.getItem(i) <<endl;

a.pop_back();
a.pop_back();
a.pop_back();
a.push_back("John Doe");
cout<<endl<<"Displaying b after changing a: "<<endl;

for (inti = 0; i<b.size(); ++i)
cout<<b.getItem(i) <<endl;
return 0;
}

Exercise 1. Predict the above program output with class List as specified in Task 1.

Exercise 2. Run the test program and compare its output to your prediction in Exercise 1. Did it behave as you expected. Explain why. You may also run a test case with the assignment operation.

Task 3: Class Dynamic Data Members

Exercise 1. Add a class copy constructor to class List to do deep copying. Use the test program from Task 2 to test it.

Exercise 2. Add a class destructor to delete dynamically allocated data.

Exercise 3. Adda public member function that overloads the assignment operator to perform deep copying(remember to deallocate dynamic data of the destination object before copying). Use the test program from Task 2 to test it.

You may add any other member functions that you deem necessary or helpful for other tasks. However, you should be careful not to provide any public member function that modifies the size or capacity of the list since these should only be changed by the constructors or when an item is added or removed from the list.

Exercise 4. Demo your final class List definition

Task 4: Update class Book with the authors list member

Exercise 1. Modify data member authorsin class Bookto be of type List. Add the following accessors and mutators (at a minimum):

a. getAuthors: returns a List object holding the authors namelist and number of authors
b. addAuthor: adds an author to the list of authors
c. removeAuthor: removes the last author added to the list.
d. clearAuthors: removes all authors.

Exercise 2. Update member functions display of class Book and classInventoryItemto

a. Output to any output stream not just cout, and

b. Output book information in the following format (all on one line):

description<tab>quantity on hand<tab>price<tab>number of authors<tab>list authors separated by tabs<tab>publisher

Exercise 3. Overload the stream insertion operator << for both class Book and class InventoryItem. Important Note: keep the display functions, and have operator<<call function display. This is particularly important for last part of this assignment.

Exercise 4. Update theread member functions of class Book and class InventoryItem to read book information from an input stream in the following format:

category, description, quantity on hand, price, number of authors, list of author names separated by commas, publisher

where category is a string that indicates the inventory item category. Assume the allowable categories are: book for books and general for anything else.

Note the following:

1. Book::read must call InventoryItem::read
2. The comma after price must be consumed by Book:read
3. You may use the following function to trim leading and trailing white spaces from strings after you call getline():

voidtrim(string&s)
{
size_t p = s.find_first_not_of(" \t\n");
s.erase(0, p);

p = s.find_last_not_of(" \t\n");
if (string::npos != p)
s.erase(p+1);
}

Exercise 5. Overload the stream extraction operator >> for both classes. Again, Do NOT replace theread function, simply have the operator >> call functionread.

Exercise 6. Use the driver program below to demo your updated Book class. You may also download a text version of it from file demoNewLab in the Lab6 folder (on EagleOnline). Make sure to include the header files with the Book class definition.

#include"book.h"
#include<vector>

//void testList();
intdemoNewBook();

intmain() {
demoNewBook();

system("pause");
return 0;
}
intdemoNewBook()
{
ifstream file("data.csv"); //Assume the name of input file is "data.csv"
if(!file)
{
cerr<<"Can't open file "<<"data.csv"<<endl;
return(EXIT_FAILURE);
}

vector<Book>bookList;
Book temp;
while (while(!file.eof())
{
file >> temp;
bookList.push_back(temp);
}
for (size_ti = 0; i<bookList.size(); ++i){
cout<<"Book "<<i+1<<": "<<bookList[i];
cout<<endl;
}

system("pause");
return 0;
}

Task 5: Polymorphism

Assume inventory items are of two categories: books or general items (category list can be expanded). As discussed above, a general inventory item has the data fields description, quantity on hand, and price whereas a book has the additional fields title, author list (number of authors and list of their names), and publisher name. Assume that inventory data files contain information from the two categories, each tagged with their category. Example;

general, IPhone 6, 35, 599.0

book, CS book, 15, 199.50, Intro to Programming with C++, 2, D.S. Malik, T. J. Holly, Pearson
general, Samsung Galaxy 7S, 376.99

book, Novel Sci Fi, 2, 6.99, The Martians, 1, Andy Weir, Media Type

Exercise 1. Consider the following test program. What do you expect it to output if run with the sample input in the box above?

#include"book.h"
#include<vector>

//void testList();
//intdemoNewBook();
inttestPolymorphism();

intmain()
{
testPolymorphism();

system("pause");
return 0;
}
//*******************************************************
// This program is used to test polymorphism of input and output operations of class Book
inttestPolymorphism()
{
ifstream file("data2.csv"); //Assume the name of input file is "data2.csv"
if(!file)
{
cerr<<"Can't open file "<<"data.csv"<<endl;
return(EXIT_FAILURE);
}
InventoryItem *temp;
string category;

getline(file, category, ','); // get the category for first item

trim(category); // remove leading and trailing spaces
if (category == "general")
temp = newInventoryItem;
elseif (category == "book")
temp = newBook;
else
{ cout<<endl<<"Invalid category"<<endl;
return(EXIT_FAILURE);
}

file >> *temp;
cout<< *temp;

getline(file, category, ','); // get the category for 2nd item
trim(category);

if (category == "general")
temp = newInventoryItem;
elseif (category == "book")
temp = newBook;
else
{ cout<<endl<<"Invalid category"<<endl;
return(EXIT_FAILURE);
}
file >> *temp;
cout<< *temp;

return 0;
}

Exercise 2. Run the test program and verify your prediction. Why isn't the book information displayed correctly?

Exercise 3. Make the required changes to base classInventoryItem so that the appropriate input and output functions are called depending on the type of object calling them i.e. make the functions polymorphic.

Exercise 4. Demo you program with the test data and program of exercise 1 above.

Final Project Demo and Submission:

Demo your project with the test driver function below and the sample input shown in the textbox above. Submit a zip file containing the final version of your project on EagleOnline by the assignment due date.

//*******************************************************

// This test function is used to demo programming assignment #3
intdemoProject()
{
ifstream file("data2.csv"); //Assume the name of input file is "data.csv"
if(!file)
{
cerr<<"Can't open file "<<"data.csv"<<endl;
return(EXIT_FAILURE);
}
vector<InventoryItem *>productList;
InventoryItem *temp;
string category;

while(!file.eof())
{
getline(file, category, ','); // get the category for next item

trim(category);
if (category == "general")
temp = newInventoryItem;
elseif (category == "book")
temp = newBook;
else
{
cerr<<endl<<"Invalid category"<<endl;
return(EXIT_FAILURE);
}

file >> *temp;
productList.push_back(temp);
}

for (inti = productList.size() -1; i>= 0 ;i--){
cout<<"Book "<<i+1<<": "<<*productList[i];
cout<<endl<<endl;
}
return 0;
}

Attachment:- Attachments.rar

Reference no: EM131479582

Questions Cloud

Who should be in charge of an organizations conduct : Prepare a 1-2 page Word document as a summary that expands on the slides and any other talking points. In a business setting this would be a handout to the staff members present.
What hardware and software you have in your lab : explain your capabilities by outlining what hardware and software you have in your lab. Include list of questions you need to ask the employee about her system.
What is the rate of annual interest on each loan : This assignment will assess the competency 7. Analyze the impact on organizational financial position of accounts receivable, inventory, and cash management.
Should there be a legal path to citizenship : HTY 110:Should there be a legal path to citizenship for the undocumented children of illegal immigrants? Why or why not?
Add a class destructor to delete dynamically allocated data : Add a class destructor to delete dynamically allocated data. Add class copy constructor to class List to do deep copying. Use test program from Task to test it.
Discuss the flexibility acse : Does adding debt increase or decrease the flexibility of a healthcare provider? Why or why not? Explain which types of debt are most desirable for a healthcare.
Formulate the problem of state feedback design : Determine the minimum volume ellipsoid that contains the reachable set R. by solving the following optimization problem
Define the concept of a learning organization : 1. Define the concept of a learning organization. Explain how does a learning organization differ from a traditional organization?
Discuss the marketing strategies actions : Scenario: Your boss has recently been elected county supervisor. She campaigned on the platform of creating a seamless system of long-term care for all.

Reviews

Write a Review

C/C++ Programming Questions & Answers

  Program for how to indicate the family member entry

Program for how to indicate the family member entry is complete

  Writing function that computes leap years

Write down function that computes leap years. Function prototype is as follows: Write function body which returns true if year is a leap year and false if year is not a leap year.

  Ruby implement primitive types

How does Ruby implement primitive types, such as those for integer and floating-point data?  3-What is the single most important practical difference between Smalltalk and C++?

  Calculate the plane coefficients

Calculate the plane coefficients (A,B,C and D)  of 3 points in a plane defined by P1, P2 and P3, and determine if the point P4 is behind or in front of the polygon surface contained within that plane.

  What is meant by value type and reference type objects

Explain what is meant by value type and reference type objects in C#. Explain the differences, providing an example of each. Write the code for an example of each. Develop your examples, instead of using examples from the textbook or the Internet

  Create a second employee object using the multi-argument

Create a second Employee object using the multi-argument constructor, setting each of the attributes with appropriate valid values.

  Write program to keep track of a hardware store''s inventory.

Use seven parallel vectors to store the information. The program must contain at least the following functions: one to input data into the vectors, one to display the menu, one to sell an item and one to print the report for the manager.

  Different types of relationships that exist between tables

What are the different types of relationships that exist between tables?

  Write a method insertat that takes four parameters

Write a method, insertAt, that takes four parameters: an array of integers; the length of the array; an integer, say insertItem; and an interger, say, index.

  Program that computes the total price of tickets

Write a program that computes the total price of tickets that a customer orders. The program should prompt the user for the number of the destination city and the number of tickets desired.

  Write another main function create three bank accounts

Write another main function - in this function create three bank accounts, then prompt the user to enter a bank account number, if the account number matches one on the three accounts then display the following menu otherwise allow the user to ent..

  Declare and use single dimension arrays

How do you declare and use single dimension arrays? How do you perform basic sort and search routines on arrays?

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd