Group
Object-Oriented Programming in C++
Objective
1. Create a class called "Product" with attributes such as name, price, and quantity in stock.
2. Implement methods for buying and selling products, which will update the stock based on the quantity purchased or sold.
3. Add a method to display the product's details including its name, price, and quantity in stock.
4. Implement a main function where you can create a product, simulate purchases and sales, and display updated product information.
Develop an Inventory system with classes for products and operations for purchase and sale.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the standard input/output library
#include <string> // Include the string library
using namespace std;
// Define the 'Product' class to represent a product in the inventory
class Product {
private:
string name; // Product name
double price; // Product price
int quantity; // Quantity in stock
public:
// Constructor to initialize the product with its details
Product(string n, double p, int q) {
name = n;
price = p;
quantity = q;
}
// Method to buy a certain quantity of the product (add to stock)
void buy(int amount) {
quantity += amount; // Increase the quantity by the purchase amount
cout << amount << " units of " << name << " purchased." << endl;
}
// Method to sell a certain quantity of the product (decrease stock)
void sell(int amount) {
if (quantity >= amount) {
quantity -= amount; // Decrease the quantity by the sale amount
cout << amount << " units of " << name << " sold." << endl;
} else {
cout << "Not enough stock to sell " << amount << " units." << endl;
}
}
// Method to display the product details (name, price, quantity)
void displayInfo() {
cout << "Product: " << name << endl;
cout << "Price: $" << price << endl;
cout << "Quantity in stock: " << quantity << endl;
}
};
int main() {
// Create a product called 'Laptop' with a price of $1000 and 10 units in stock
Product laptop("Laptop", 1000.0, 10);
// Display the initial product information
laptop.displayInfo();
// Simulate a purchase of 5 units
laptop.buy(5);
// Simulate a sale of 8 units
laptop.sell(8);
// Display the updated product information
laptop.displayInfo();
// Attempt to sell more units than available
laptop.sell(10);
return 0; // Return 0 to indicate successful execution
}
Output
Product: Laptop
Price: $1000
Quantity in stock: 10
5 units of Laptop purchased.
8 units of Laptop sold.
Product: Laptop
Price: $1000
Quantity in stock: 7
Not enough stock to sell 10 units.