Adding products
- C++ course
- Beginner
- Lesson 49/116
- 6 min
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.
Practice 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.
Starter code
#include <iostream>
#include <string>
#include <vector>
struct Product {
std::string name;
double price;
int quantity;
};
struct Cart {
std::vector<Product> items;
// Write the addItem function here
};
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;
}Sample 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;
}Expected output
added
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the addItem body
void addItem(Product p) {
____;
}
void addItem(Product p) {
items.push_back(p);
}
Explanation: items.push_back(p) appends the product to the vector.
2 Match each method to its job
| Term | Meaning |
|---|---|
addItem |
Adds a product |
push_back |
Appends to a vector |
getSubtotal |
Returns subtotal |
printCart |
Prints the cart |
3 What does cart.addItem(p) do?
cart.addItem(p);- Removes a product
- Adds a product to the cart Correct answer
- Computes the total
- Updates the quantity
Explanation: addItem appends p to the cart's items vector.