Unit 2- Hands-On Scenario Based Program - Solution
Unit 2- Hands-On Scenario Based Program - Solution
Develop a shopping cart system that utilizes operator overloading through friend
functions. The program should:
Output
Cart 1 Details:
Cart ID: 1
Total Items: 3
Total Amount: $37.5
Cart 2 Details:
Cart ID: 2
Total Items: 5
Total Amount: $40
Merged Cart Details (Cart 3):
Cart ID: 4
Total Items: 8
Total Amount: $77.5
class Bill {
private:
static int billCounter; // Static counter to track total bills generated
int billNumber; // Unique bill number
float totalAmount; // Total bill amount
public:
// Constructor to initialize the bill
Bill() {
billNumber = ++billCounter; // Assign a unique bill number
totalAmount = 0.0f;
}
class Restaurant {
private:
static const int menuSize = 5; // Fixed menu size
string menuItems[menuSize] = {"Burger", "Pizza", "Pasta", "Salad", "Soda"}; // Menu items
float menuPrices[menuSize] = {5.99, 8.99, 7.49, 4.99, 1.99}; // Prices of items
public:
// Method to display the menu
void displayMenu() {
cout << "\nMenu:\n";
for (int i = 0; i < menuSize; ++i) {
cout << i + 1 << ". " << menuItems[i] << " - $" << menuPrices[i] << endl;
}
}
// Method to create a bill
void createBill() {
Bill bill;
int itemChoice, quantity;
char moreItems;
do {
displayMenu();
cout << "\nEnter the item number to order (0 to stop): ";
cin >> itemChoice;
cout << "Do you want to add another item? (y/n): ";
cin >> moreItems;
} while (moreItems == 'y' || moreItems == 'Y');
int main() {
Restaurant restaurant;
char continueBilling;
do {
restaurant.createBill();
cout << "\nDo you want to generate another bill? (y/n): ";
cin >> continueBilling;
} while (continueBilling == 'y' || continueBilling == 'Y');
cout << "\nTotal bills generated: " << Bill::getTotalBillsGenerated() << endl;
return 0;
}
1. #include <iostream>
using namespace std;
class ShoppingCart {
private:
static int cartCounter; // Static counter for unique cart IDs
int cartID; // Unique cart ID
int totalItems; // Total number of items in cart
float totalAmount; // Total cost of items
public:
// Constructor
ShoppingCart() {
cartID = ++cartCounter; // Assign unique cart ID
totalItems = 0;
totalAmount = 0.0f;
}
// Friend functions to overload > and < for cart comparison based on total amount
friend bool operator>(const ShoppingCart &cart1, const ShoppingCart &cart2);
friend bool operator<(const ShoppingCart &cart1, const ShoppingCart &cart2);
int main() {
ShoppingCart cart1, cart2, cart3;
return 0;
}