CodeBlanks Logo Icon CodeBlanks

Cart design

Design the struct and vector for the shopping cart.

Cart design

In this project we will build a shopping cart application step by step. The first step is to design the Product structure that represents an item in the cart. In C++ you use a struct to group related fields under one roof.

A product has three core fields: name (std::string), price (double) and quantity (int). Writing struct Product { std::string name; double price; int quantity; }; brings these three together. You will see more about struct in a later level; here we use it just to group data.

struct syntax

A struct is a data type that holds several variables. Its form is struct Name { type field1; type field2; };; the semicolon after the closing brace is mandatory.

To use a struct you first declare a variable, then access its fields with a dot: Product p; p.name = "Notebook"; p.price = 25.0; p.quantity = 2;. This way the three related pieces travel together and can be passed to a function as a single parameter.

Practice Define the Product struct

Define a struct Product with the fields std::string name, double price and int quantity. main already creates a product and prints its name; you only need to define the struct. The output must be Notebook.

Starter code

main.cpp
#include <iostream>
#include <string>

// Write the Product struct here

int main() {
    Product p;
    p.name = "Notebook";
    p.price = 25.0;
    p.quantity = 2;
    std::cout << p.name << std::endl;
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

struct Product {
    std::string name;
    double price;
    int quantity;
};

int main() {
    Product p;
    p.name = "Notebook";
    p.price = 25.0;
    p.quantity = 2;
    std::cout << p.name << std::endl;
    return 0;
}

Expected output

Notebook

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which type fits the product name in the Product struct?

main.cpp
struct Product { ... name ...; };
  • std::string Correct answer
  • int
  • double
  • bool

Explanation: Text is held in std::string.

2 Write the struct name

Question
struct ____ {
    std::string name;
    double price;
    int quantity;
};
Answer
struct Product {
    std::string name;
    double price;
    int quantity;
};

Explanation: The struct is named Product and starts with a capital letter.

3 Match each field to its type

Term Meaning
name std::string
price double
quantity int
items std::vector<Product>

All lessons in Beginner