Start learning free

LESSON 66 OF 69 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in C++: LineItem and Cart Classes

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • Public fields string name, double price, int quantity.
  • LineItem(string name, double price, int quantity) stores the three values using this->.
  • double subtotal() returns price * quantity.

Cart

  • It keeps its items in a private vector<LineItem> items.
  • void add(LineItem item) pushes the item onto the vector.
  • double total() returns the sum of the subtotals of all items: start double sum = 0, loop with for (auto& item : items), return sum.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

Remember the public: and private: labels and the ; after each class. cout prints the double 75 as 75. The driver lives in Solution::mainFunction().

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

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;
    }
};

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write class LineItem { public: ... }; first, then class Cart.

for (auto& item : items) sum += item.subtotal();

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;
    }
};

STEP 1 OF 19
    Ctrl + Enter to check

    C++ · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in C++, explained

    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

    1. Declare the class and write its closing }; straight away.
    2. Open a public: section and declare string name;.
    3. Declare double price;. A double holds a number with decimals, in case a price isn't whole.
    4. Declare int quantity;, since the number of items bought is always whole.
    5. Write the constructor. It has the same name as the class, no return type, and takes the three values.
    6. Store each value with this->name = name; and the same for price and quantity. The parameters share their names with the fields, so inside the constructor the bare name means the parameter, and this-> selects the field.
    7. Add subtotal as a method returning double, and return price * quantity.

    Building Cart

    1. Declare the class below LineItem, with its closing };.
    2. Add the private field vector<LineItem> items;.
    3. Open a public: section for the methods the driver calls.
    4. Write add as a void method taking a LineItem named item, and append it with items.push_back(item).
    5. Start total as a method returning double.
    6. Create double sum = 0; so an empty cart totals 0.
    7. Loop over the rows with for (auto& item : items) and add item.subtotal() to sum on the same line.
    8. Return sum after 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. LineItem comes before Cart because Cart uses 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. auto lets the compiler work out the type, and the & makes item a reference to the element in the vector instead of a copy. Without the & the code still gives the right total, but every row, including its string, is copied on each pass.
    • add takes its argument by value. The row passed in is copied into the parameter, and push_back stores another copy. Because LineItem is 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 a LineItem in place and hands it straight to add, with no variable needed.
    • Doubles print compactly. cout shows the double 75 as 75. 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 sum uninitialised. A local double declared without a value holds garbage. Write double sum = 0;.
    • Putting sum += ... after the loop. The loop line must add each row, and the return must be outside the loop. Returning inside the loop would stop after the first row.
    • Forgetting this->. Writing name = 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 vector of 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.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free