C++ Object and Classes Programming -- Helpful comments is greatly appreciated!!
ID: 3587033 • Letter: C
Question
C++ Object and Classes Programming -- Helpful comments is greatly appreciated!!
Create an Account class that a bank might use to represent customers' bank accounts. Include a data member of type double to represent the account balance. Provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it's greater than or equal to 0. If not, set the balance to 0 and display an error message indicating that the initial balance was invalid. Provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and ensure that the debit amount does not exceed the Account's balance. If it does, the balance should be left unchanged and the function should print a message indicating "Debit amount exceeded account balance." Member function getBalance should returrn the current balance. Create a program that creates two Account objects and tests the member functions of class Account.Explanation / Answer
#include<iostream>
using namespace std;
class Account{
//declare a acc_bal variable
private:
double acc_bal;
public:
// constructor with an argument to set the initial balance
Account(int bal){
if(bal<0){
cout << "Initial balance was invalid." << endl;
acc_bal = 0;
}
else{
acc_bal = bal;
}
}
//credit method to add amount to account balance
void credit(int bal){
acc_bal += bal;
cout << "Added " << bal << " to account" << endl;
}
//debit method to Withdrawn amount from account
void debit(int bal){
if(bal < acc_bal){
acc_bal -= bal;
cout << "Withdrawn " << bal << " from account " << endl;
}
else{
cout << "Debit amount exceeded account balance" << endl;
}
}
//this method returns the current account balance.
int getBalance(){
return acc_bal;
}
};
int main(){
Account acc(-1);
acc.credit(100);
cout << "Balance:" << acc.getBalance() << endl;
acc.debit(200);
cout << "Balance:" << acc.getBalance() << endl;
acc.debit(50);
cout << "Balance:" << acc.getBalance() << endl;
return 0;
}
/*
sample output
Initial balance was invalid.
Added 100 to account
Balance:100
Debit amount exceeded account balance
Balance:100
Withdrawn 50 from account
Balance:50
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.