Group
Object-Oriented Programming in C++
Objective
1. Define a class called "BankAccount" with a private attribute: balance (double).
2. Add a constructor to initialize the balance to zero.
3. Implement a method to deposit money into the account.
4. Implement a method to withdraw money from the account, ensuring that the balance does not go negative.
5. Implement a method to check and display the current balance.
6. In the main function, create an object of the BankAccount class, deposit money, withdraw money, and check the balance.
Develop a BankAccount class with methods to deposit, withdraw, and check balance.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the standard input/output library
using namespace std;
// Define the 'BankAccount' class
class BankAccount {
private:
double balance; // Private attribute for the account balance
public:
// Constructor to initialize the balance to zero
BankAccount() {
balance = 0.0; // Set the balance to 0 initially
}
// Method to deposit money into the account
void deposit(double amount) {
if (amount > 0) { // Ensure the deposit amount is positive
balance += amount; // Add the amount to the balance
cout << "$" << amount << " deposited successfully." << endl;
} else {
cout << "Deposit amount must be positive!" << endl;
}
}
// Method to withdraw money from the account
void withdraw(double amount) {
if (amount > 0 && amount <= balance) { // Ensure withdrawal is valid
balance -= amount; // Subtract the amount from the balance
cout << "$" << amount << " withdrawn successfully." << endl;
} else if (amount > balance) {
cout << "Insufficient balance!" << endl; // Handle insufficient balance
} else {
cout << "Withdrawal amount must be positive!" << endl; // Handle invalid withdrawal
}
}
// Method to check and display the current balance
void checkBalance() {
cout << "Current balance: $" << balance << endl; // Display the balance
}
};
int main() {
// Create a 'BankAccount' object
BankAccount myAccount;
// Deposit money into the account
myAccount.deposit(500.0);
// Withdraw money from the account
myAccount.withdraw(200.0);
// Check and display the current balance
myAccount.checkBalance();
// Try an invalid withdrawal (insufficient balance)
myAccount.withdraw(400.0);
// Check balance again
myAccount.checkBalance();
return 0; // Return 0 to indicate successful execution
}
Output
$500 deposited successfully.
$200 withdrawn successfully.
Current balance: $300
Insufficient balance!
Current balance: $300