Problem overview
A shop keeps its orders in a cart. The lesson builds two classes that work together. A LineItem is one row of the cart: a product name, a price and a quantity. A Cart holds many rows and adds them up. The cart has line items, which is composition, rather than being one.
LineItem has public fields string name, double price and int quantity, a constructor that takes the three values, and a method double subtotal() that returns price * quantity. Cart keeps a private vector<LineItem> items, a method void add(LineItem item) and a method double total() that returns the sum of every item's subtotal.
The code at the bottom of the starter checks an empty cart, then one subtotal, then builds a cart and prints the total twice. An apple at price 5 with quantity 3 has a subtotal of 15. The cart then holds the apple and bread at 20 times 3, so the total is 15 + 60 = 75. Adding milk at 10 times 2 brings the total to 95. The output:
Empty: 0
Subtotal: 15
Total: 75
Total: 95
Approach: each class does its own job
The design gives each class one responsibility. A LineItem knows its own price and quantity, so it is the one that knows how to compute its subtotal. The Cart doesn't reach into the fields of its rows to multiply them. It asks each row for its subtotal() and adds the answers. If the way a row is priced changes later, only LineItem has to change.
The cart's total is worked out on every call, from the rows it holds at that moment. It isn't stored in a field. That is why adding the milk changes the next total from 75 to 95, and why an empty cart has a total of 0: the loop has nothing to add, so sum keeps its starting value.
The items vector is private, so code outside the cart can only grow it through add. The rows keep the order in which they were added.
Step by step
Building LineItem
- Declare the class and write its closing
};straight away. - Open a
public:section and declarestring name;. - Declare
double price;. Adoubleholds a number with decimals, in case a price isn't whole. - Declare
int quantity;, since the number of items bought is always whole. - Write the constructor. It has the same name as the class, no return type, and takes the three values.
- Store each value with
this->name = name;and the same forpriceandquantity. The parameters share their names with the fields, so inside the constructor the bare name means the parameter, andthis->selects the field. - Add
subtotalas a method returningdouble, and returnprice * quantity.
Building Cart
- Declare the class below
LineItem, with its closing};. - Add the private field
vector<LineItem> items;. - Open a
public:section for the methods the driver calls. - Write
addas avoidmethod taking aLineItemnameditem, and append it withitems.push_back(item). - Start
totalas a method returningdouble. - Create
double sum = 0;so an empty cart totals 0. - Loop over the rows with
for (auto& item : items)and additem.subtotal()tosumon the same line. - Return
sumafter the loop. This line runs once, when every row has been added.
The solution in C++
class LineItem {
public:
string name;
double price;
int quantity;
LineItem(string name, double price, int quantity) {
this->name = name;
this->price = price;
this->quantity = quantity;
}
double subtotal() {
return price * quantity;
}
};
class Cart {
private:
vector<LineItem> items;
public:
void add(LineItem item) {
items.push_back(item);
}
double total() {
double sum = 0;
for (auto& item : items) sum += item.subtotal();
return sum;
}
};
class Solution {
public:
void mainFunction() {
Cart empty;
cout << "Empty: " << empty.total() << endl;
LineItem apple("Apple", 5, 3);
cout << "Subtotal: " << apple.subtotal() << endl;
Cart cart;
cart.add(apple);
cart.add(LineItem("Bread", 20, 3));
cout << "Total: " << cart.total() << endl;
cart.add(LineItem("Milk", 10, 2));
cout << "Total: " << cart.total() << endl;
}
};
C++ details worth knowing
- Order matters.
LineItemcomes beforeCartbecauseCartuses it, and both come before the code that uses them. - Range-based
for.for (auto& item : items)visits each element in turn with no index.autolets the compiler work out the type, and the&makesitema reference to the element in the vector instead of a copy. Without the&the code still gives the right total, but every row, including itsstring, is copied on each pass. addtakes its argument by value. The row passed in is copied into the parameter, andpush_backstores another copy. BecauseLineItemis a plain class with ordinary fields, those copies are made automatically and the cart owns its own rows.- Temporary objects.
cart.add(LineItem("Bread", 20, 3))builds aLineItemin place and hands it straight toadd, with no variable needed. - Doubles print compactly.
coutshows thedouble75 as75. With fractional prices, a cart with a pen at 1.5 times 4 and a cup at 2.25 times 2 totals 10.5, and adding gum at 0.99 times 3 gives 13.47.
Complexity
add is amortised O(1). total visits each of the n rows once, so it takes O(n) time and O(1) extra space, because it only keeps one running sum. Working the total out each time costs a loop per call, but it can never go out of date.
Edge cases and common mistakes
- Starting
sumuninitialised. A localdoubledeclared without a value holds garbage. Writedouble sum = 0;. - Putting
sum += ...after the loop. The loop line must add each row, and thereturnmust be outside the loop. Returning inside the loop would stop after the first row. - Forgetting
this->. Writingname = name;in the constructor assigns the parameter to itself and leaves the field unset. - Missing semicolons after the classes. Each class ends with
};. - Making the total a stored field. A stored total would need updating on every change. Computing it on demand keeps it correct.
Testing
Besides the driver, try a cart with no items (total 0), a single row with quantity 0 (subtotal 0), and the fractional example above. The cart with the pen and the cup prints 10.5, and after adding the gum it prints 13.47:
10.5
13.47
Key takeaways
- A cart has line items: one class holds a
vectorof the other (composition). - Give each class the knowledge it owns: the row computes its subtotal, the cart sums the rows.
- Compute the total when asked, starting the sum at 0 so an empty cart works.
