cppbeginner10 minutes

Simple Bank Account Management System

Build a basic bank account management mini-project in C++ that allows creating an account, depositing money, withdrawing money, and showing the current balance.

Challenge prompt

Create a C++ program that simulates a simple bank account system. You need to implement a class named BankAccount with the following functionalities: 1. A constructor that initializes the account with the owner's name and an initial balance (default to 0). 2. A method deposit(double amount) that adds money to the balance. 3. A method withdraw(double amount) that subtracts money if enough balance exists, otherwise prints "Insufficient funds". 4. A method getBalance() that returns the current balance. 5. A method display() that prints the account owner's name and current balance in a friendly format. Your program should demonstrate creating at least one account, making some deposits and withdrawals, and then displaying the final account balance.

Guidance

  • Define a class with private variables for owner's name and balance.
  • Use methods to modify and access the balance safely.
  • Make sure withdrawals do not reduce the balance below zero.
  • Test your class by creating objects and calling methods in main().

Hints

  • Use simple conditional statements to check funds before withdrawal.
  • The constructor should initialize the balance using an initializer list or inside the constructor body.
  • Use cout for displaying output.

Starter code

#include <iostream>
#include <string>

using namespace std;

class BankAccount {
private:
    string owner;
    double balance;

public:
    // Constructor
    BankAccount(string ownerName, double initialBalance = 0) {
        // Initialize variables here
    }

    // Deposit money
    void deposit(double amount) {
        // Add amount to balance
    }

    // Withdraw money
    void withdraw(double amount) {
        // Subtract amount if possible
    }

    // Get balance
    double getBalance() {
        return balance;
    }

    // Display account info
    void display() {
        // Print owner and balance
    }
};

int main() {
    BankAccount account1("Alice");
    account1.deposit(1000);
    account1.withdraw(500);
    account1.withdraw(600); // Should print insufficient funds
    account1.display();
    return 0;
}

Expected output

Insufficient funds Account owner: Alice Current balance: 500

Core concepts

classesmethodsconditionalsbasic I/O

Challenge a Friend

Send this duel to someone else and see if they can solve it.