Skip to content

Lab · C++ Programming (modern C++ and DSA)

Lab: a UPI wallet with references and pointers

Labbeginner· about 2 hours· 4 steps

The brief

Build the core of a small UPI wallet: functions that change the balance through references, totals over a list of payments, a pointer to the largest payment that is nullptr when there are none, and a check that a UPI ID looks like name@bank.

Why it matters

Payment apps such as PhonePe, Google Pay and Paytm handle crores of wallet updates a day. The rules you practise here matter there: change shared state only through clear references, never read through a null pointer, and validate every ID a user types before money moves.

Skills you practise

  • pass by reference (int&)
  • pass by const reference
  • std::vector and range-for
  • pointers and nullptr
  • std::string find, size and loops

You need

  • g++ 11 or newer (MinGW-w64 via MSYS2 on Windows, build-essential on Ubuntu, Xcode command line tools on macOS, where g++ runs Apple clang)
  • A terminal (Git Bash, MSYS2 or PowerShell on Windows)

What you will have at the end

wallet.cpp: wallet functions that use references, a const-reference total, a nullptr-safe largest() and a UPI ID check, building with no warnings.

How it is marked (rubric, 100 points)
Correct resultsEvery check passes, including the failed payment, the empty list and all six UPI IDs.40
Right way to passint& only where the function changes the value; const std::vector<int>& and const std::string& for read-only inputs.25
Safe pointerslargest returns nullptr for an empty list and main checks the pointer before using it.20
ExplainedYou can say when to pass by value, by reference and by const reference.15

0/4 steps done

Step 1 of 4

Change the balance through a reference

addMoney and pay change the caller's balance: 2500, 2380, 1481, and the Rs 5000 payment fails.

A function that takes int balance gets a copy, so the wallet never changes. Take int& balance instead: the parameter is another name for the caller's variable. pay returns false, and changes nothing, when the balance is too low. In main, start at 500, add 2000, pay 120, pay 899, then try to pay 5000, and print the four lines shown.

void addMoney(int& balance, int amount) {
    balance += amount;   // changes the caller's variable
}
Without the &, only a copy changes.
Run this on your machine, then paste the output below
$ g++ -std=c++17 -Wall -Wextra -o wallet wallet.cpp; ./wallet
Your notes: wallet.cpp

Write down each command you ran. It goes into your project summary.