C++
Adding products
Write the function that adds products to the cart.
The addItem function
The Product struct is ready; now we will write an addItem function to add products to the cart. The Cart struct already has a std::vector<Product> items field; this vector holds the added products.
std::vector is C++'s automatically growing array; you will see more about it later. The addItem(Product p) function calls items.push_back(p) in its body, which appends p to the end of the vector. The function returns no value, so its type is void.
vector and push_back
std::vector<T> is an array structure whose size grows automatically. items.push_back(x) appends x, items.size() gives the count, and items[i] accesses by index.
You must declare a vector with std::vector<Product> items; before using it. In the Cart struct this declaration is already present. In this project we will use only push_back and size; iterating with loops will come in later lessons.
Exercise Write the addItem function
Add an addItem function inside the Cart struct. Its signature must be void addItem(Product p). The body should call items.push_back(p);. main already adds a product and prints added; you only need to write the function.
Show example solution
#include <iostream>
#include <string>
#include <vector>
struct Product {
std::string name;
double price;
int quantity;
};
struct Cart {
std::vector<Product> items;
void addItem(Product p) {
items.push_back(p);
}
};
int main() {
Cart cart;
Product p;
p.name = "Notebook";
p.price = 25.0;
p.quantity = 2;
cart.addItem(p);
std::cout << "added" << std::endl;
return 0;
}
Test yourself
-
Write the addItem body
void addItem(Product p) {
____;
}
Show answer
void addItem(Product p) {
items.push_back(p);
}
-
Match each method to its job
- addItem
- Adds a product
- push_back
- Appends to a vector
- getSubtotal
- Returns subtotal
- printCart
- Prints the cart
-
What does cart.addItem(p) do?
cart.addItem(p);
- Removes a product
- Adds a product to the cart
- Computes the total
- Updates the quantity
Show answer
Adds a product to the cart — addItem appends p to the cart's items vector.
Next lesson: Calculating totals