Intermedient Programming Midterm
Intermedient Programming Midterm
Define a class Grocery that represents items you can pick up at the grocery store.
● Each item has a char * name, an integer number of units and a price per unit (float).
● All member variables should be private and you need to write getter and setter methods
for each variable.
● You should also make a Grocery constructor and destructor. The non-empty constructor
(if you make more than one) should take in the item's name and price as parameters.
● Example: you might pick up a can of soup (3.99 and 4 boxes of cereal at 4.99 each.
● Your Grocery class should also implement a function "totalPrice" that calculates the total
price for buying that item. The cereal would return 19.96.
● Implement a printInfo function that has a void return method and prints out information
about the item (name, the units, price per unit, and total cost.
int main() {
// Create instances of the Grocery class
Grocery soup("Soup", 3.99);
Grocery cereal("Cereal", 4.99);
return 0;
}
#include <iostream>
#include <string.h>
class Grocery {
private:
char* name;
int units;
float price;
public:
// Constructor with name and price parameters
Grocery(const char* n, float p) {
name = new char[strlen(n) + 1];
strcpy(name, n);
price = p;
units = 0;
}
// Empty constructor
Grocery() {
name = new char[1];
name[0] = '\0';
price = 0;
units = 0;
}
// Destructor
~Grocery() {
delete[] name;
}
// Calculate tax
float tax = totalCost * 0.15;
return tax;
}
int main() {
// Declare an array of Grocery objects
const int ARRAY_SIZE = 3;
Grocery* groceries[ARRAY_SIZE];
groceries[0] = new Grocery("Soup", 3.99);
groceries[0]->setUnits(2);
groceries[1] = new Grocery("Cereal", 4.99);
groceries[1]->setUnits(3);
groceries[2] = new Grocery("Bread", 2.49);
groceries[2]->setUnits(4);
delete singleGrocery[0];
return 0;
}