This is a program I wrote for a test (don't worry, it has ended). I implemented composition and aggregation as wanted by the question. However, I didn't get the output that I wanted.
Here is the code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Name
{
private:
string firstName, lastName;
public:
Name(string fN, string lN)
{
fN = firstName;
lN = lastName;
}
string getFullName()
{
string space = " ";
string full;
firstName.append(space);
full = firstName.append(lastName);
return full;
}
};
class Product
{
private:
string name, category;
double price;
int quantity;
public:
Product()
{
name = " ";
category = " ";
price = 0;
quantity = 0;
}
Product(string n, string c, double p)
{
name = n;
category = c;
price = p;
}
string getName()
{
return name;
}
string getCategory()
{
return category;
}
double getPrice()
{
return price;
}
int getQuantity()
{
return quantity;
}
void setQuantity(int q)
{
quantity = q;
}
};
class Customer
{
private:
string address;
int numProduct;
Product *product;
public:
Name name;
Customer(string fn, string ln, string add) : name(fn, ln)
{
address = add;
numProduct = 0;
Product **ptr = new Product*[4];
}
void buy(Product p, int num)
{
int i=0;
if (i<4)
{
num = numProduct;
p.setQuantity(num);
i++;
//p[i].setQuantity(num);
}
else
{
cout << "Sorry!! You already reached the maximum number of products purchased." << endl;
}
}
void print()
{
double total=0;
cout << left << setw(7) << "Name" << ": " << name.getFullName() << endl;
cout << "Address: " << address << endl;
cout << "Number of products purchased: 4" << endl;
cout << left;
cout << setw(4) << "No" << setw(15) << "Product Name" << setw(10) << "Category"
<< setw(10) << "Quantity" << setw(20) << "Unit Price (RM)" << setw(15) << "Amount (RM)" << endl;
for (int i=0; i<4; i++)
{
cout << left;
cout << fixed << setprecision(2);
cout << setw(4) << i+1 << setw(15) << product[i].getName() << setw(15) << product[i].getCategory()
<< setw(10) << product[i].getQuantity() << setw(20) << product[i].getPrice() << setw(15) <<
product[i].getPrice()*product[i].getQuantity() << endl;
total += product[i].getPrice()*product[i].getQuantity();
}
cout << fixed << setprecision(2) << "Total price = " << total;
}
};
int main() {
Customer cust("Amir", "Jalil", "Masai, Johor");
Product p1("Jacob", "Biscuit", 14.8);
Product p2("Twister", "Drink", 7.5);
Product p3("Ayamas", "Nugget", 18.4);
Product p4("Oreo", "Biscuit", 3.8);
cust.buy(p4, 5);
cust.buy(p2, 4);
cust.buy(p3, 2);
cust.buy(p1, 3);
cust.print();
return 0;
}
Here is the output that I should get:
But, this is the output that I got:
I know that things gone wrong in the Customer
class, but I don't know how to solve it. If needed, the below is the instruction for the class.