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

  Lab9 c lab 9 c i request this twice but no answer on this

lab 9 c ltbrgti request this twice but no answer on this please could you check this for

  Read in data from an input file (qstr.txt).

It will print the output and say that it is NOT palindrome which leads me to believe it is missing something somehow.

  Our string class always deletes the old character

Our String class always deletes the old character buffer and reallocates a new character buffer on assignment or in the copy constructor. This need not be done if the new value is smaller than the current value

  8-bit or 16-bit mode, and the prescaling ratio

8-bit or 16-bit mode, and the prescaling ratio. You can assume XTAL = 10M Hz or at the frequency you specify.

  Consider the world of libraries

Consider the world of libraries. A library has books, videos, and CDs that it loans to its users. All library material has an id# and a title.

  Write a program to swap value of two variables without using

Write a program to swap value of two variables without using third variable. Write a program which input three numbers and display the largest number using ternary operator. Write a program which accepts amount as integer and display total number of ..

  Perpetual preferred stock

1) Johnson Corporation JUST PAID a dividend of $4.63.  The expected growth rate on dividends is 8 percent.  What is the current price of this stock if the required rate of return is 10 percent?

  Write a random file

Write a program in C that write a random file (test write speed) then read that same file and calculate the speed of the write. (please DON'T use hdparm to test the read speed)

  What exactly is an array

What exactly is an array? Can you give a simple example of it in C++ code, as well

  Program that calculate and print the parking charges

Write a program that will calculate and print the parking charges for each of three customers who parked their cars in this garage yesterday.

  Algorithm to determine which items to take to max weight

Write an algorithm to determine which items to take to maximize the weight of his loot bag. He cannot take a fraction of an item and each item must be taken, or left behind. Loot bag size is Z and and the input is an array of item wieghts as integers..

  Write a program that will store 10 integers into an array

Write a program that will store 10 integers into an array. Only accept integers between -100 and 100. Display those integers. You must then square those integers by CALLING A FUNCTION to square each individual integer. That function must be called, s..

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