Start learning free

LESSON 67 OF 69 · PROJECTS: OBJECT-ORIENTED

Vending Machine in C++: A Class with State and Credit

Practice Read the full explanation

Build a VendingMachine class for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with VendingMachine m;.

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Declare double credit = 0; and double price = 150; under private:; no constructor is needed.
  • void insert(double amount) adds amount to the credit. Nothing is printed or returned.
  • string select() tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • double refund() returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

class Solution {
public:
    void mainFunction() {
        VendingMachine m;
        m.insert(50);
        cout << m.select() << endl;
        m.insert(150);
        cout << m.select() << endl;
        cout << "Refunded: " << m.refund() << endl;
        m.insert(150);
        cout << m.select() << endl;
        cout << "Refunded: " << m.refund() << endl;
        m.insert(100);
        cout << m.select() << endl;
        cout << "Refunded: " << m.refund() << endl;
    }
};

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Cast the missing amount to int and turn it into text with to_string((int)(price - credit)). Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved variable, not credit.

class VendingMachine {
private:
    double credit = 0;
    double price = 150;
public:
    void insert(double amount) {
        credit += amount;
    }

    string select() {
        if (credit < price) return "Need " + to_string((int)(price - credit)) + " more";
        credit -= price;
        return "Dispensing!";
    }

    double refund() {
        double r = credit;
        credit = 0;
        return r;
    }
};

STEP 1 OF 15
    Ctrl + Enter to check

    C++ · PROJECTS: OBJECT-ORIENTED

    Vending Machine in C++, explained

    Problem overview

    You write a VendingMachine class for a machine that sells one kind of item at a fixed price of 150. The machine remembers the money inserted so far, its credit, and offers three actions:

    • void insert(double amount) adds money to the credit. It prints and returns nothing.
    • string select() tries to buy one item. With too little credit it returns "Need N more", where N is the missing amount as a whole number, and leaves the credit alone. Otherwise it subtracts the price from the credit and returns "Dispensing!". Exact payment works, and any extra money stays in the credit.
    • double refund() returns the whole credit and sets it back to 0, so asking again returns 0.

    The code at the bottom of the starter runs three purchases. Inserting 50 is short by 100, so the machine answers Need 100 more. Inserting 150 more makes the credit 200, so it dispenses and keeps 50 (200 - 150), and the refund is 50. Next, 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100 and the refund is 100:

    Need 100 more
    Dispensing!
    Refunded: 50
    Dispensing!
    Refunded: 0
    Need 50 more
    Refunded: 100

    Approach: state plus methods that change it

    A class is a good fit here because the machine has memory. Each VendingMachine keeps its own credit between calls, and the methods read and update it. The two fields are private, double credit = 0; and double price = 150;, so only the machine's own methods can change them. Their default values are written where they are declared, so a plain VendingMachine m; already starts with no money and a price of 150, and no constructor is needed.

    The key design point is when the credit changes. select has two outcomes and only one of them spends money:

    • When the credit is too low, select only reports the shortfall. The customer may insert more and try again, so nothing is subtracted.
    • When the credit is enough, select subtracts the price. If you forget this, the leftover credit is wrong and the refund gives back too much.

    refund has a different trap. It must return the old credit and also reset it to 0. After credit = 0 the old value is gone, so refund saves it in a local variable first.

    Step by step

    1. Declare VendingMachine and write its closing }; right away.
    2. Open the private: part. The credit and the price are the machine's own business.
    3. Add double credit = 0;: a new machine holds no money.
    4. Add double price = 150;: every item costs 150.
    5. Open the public: part so the code outside can call the methods.
    6. Start insert as a void method taking a double named amount.
    7. Add the amount to credit with +=. It adds to what is already there; it doesn't replace it.
    8. Start select as a method with no parameters that returns a string.
    9. Handle too little money. If credit < price, return the message built from the missing amount. The amount is cast to int, then to_string turns it into text that can join the message.
    10. Charge the price below that if: credit -= price;. This line is reached only when the credit covers the price.
    11. Return "Dispensing!".
    12. Start refund as a method with no parameters that returns a double.
    13. Save the credit in a double named r.
    14. Reset credit to 0.
    15. Return r, the saved money. Returning credit here would return 0.

    The solution in C++

    class VendingMachine {
    private:
        double credit = 0;
        double price = 150;
    public:
        void insert(double amount) {
            credit += amount;
        }
    
        string select() {
            if (credit < price) return "Need " + to_string((int)(price - credit)) + " more";
            credit -= price;
            return "Dispensing!";
        }
    
        double refund() {
            double r = credit;
            credit = 0;
            return r;
        }
    };
    
    class Solution {
    public:
        void mainFunction() {
            VendingMachine m;
            m.insert(50);
            cout << m.select() << endl;
            m.insert(150);
            cout << m.select() << endl;
            cout << "Refunded: " << m.refund() << endl;
            m.insert(150);
            cout << m.select() << endl;
            cout << "Refunded: " << m.refund() << endl;
            m.insert(100);
            cout << m.select() << endl;
            cout << "Refunded: " << m.refund() << endl;
        }
    };
    

    C++ details worth knowing

    • Default member initialisers. double credit = 0; inside the class gives every new object that starting value. This is why VendingMachine m; works without a constructor.
    • Why cast to int. to_string on a double prints six decimals. With a price of 150 and a credit of 50.5, to_string(price - credit) gives 99.500000, while to_string((int)(price - credit)) gives 99. The cast truncates toward zero, so a fractional shortfall is cut down, not rounded. With the whole-number amounts of this lesson the result is exact.
    • Building a message. "Need " + to_string(...) + " more" works because to_string returns a std::string, and adding a string to a string literal is allowed. Two literals can't be added directly: "Need " + " more" doesn't compile.
    • Doubles for money. Whole numbers such as 50, 150 and 200 are represented exactly in a double, so the comparison credit < price is reliable here. With fractional amounts, tiny representation errors can matter.

    Complexity

    Every method does a fixed amount of work: a comparison, an addition or a subtraction, so each call is O(1) in time and the machine uses O(1) space for its two numbers.

    Edge cases and common mistakes

    • Using <= instead of <. Exact payment must work. With credit <= price, inserting exactly 150 would be refused.
    • Subtracting before checking. The credit must stay unchanged when the answer is Need N more.
    • Forgetting credit -= price;. The refund after a purchase would return the whole amount that was inserted. In the driver it would print 200 instead of 50.
    • Returning credit after resetting it. The refund would always be 0. Return the saved variable.
    • Replacing instead of adding. credit = amount; in insert loses money that was already inserted.

    Key takeaways

    • Private fields with default values hold the machine's state between calls.
    • Change the state only on the branch that should change it: only a successful select charges the price.
    • Save a value in a local variable before resetting it when you also need to return it.
    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