I am creating a program which includes a parent class Account and a derived class BankAccount. Initially, I have to set the balance in account to be 5000. And when certain transactions are made, this balance should be updated. Also, whenever the program is closed, the program should return the latest balance. Below is my code. However, I am not able to initialize the constructor properly and hence, initial balance is never set correctly. Please tell me what I am doing wrong.
class Account
{
public:
void setCashBal(); //updates the cash balance in account whenever a transaction is made
double getCashBal(); //retrieves recent cash balance
protected:
double cash_balance;
};
void Account::setCashBal()
{
double initial_bal;
ifstream read_cash_file("cash_bal_file.txt", ios_base::in);
int count = 0;
if (read_cash_file.is_open()) //check whether the file could be openend
{
while (!(read_cash_file.eof())) //reading until the end of file
{
count = count + 1;
break;
}
read_cash_file.close();
if (count == 0)//if the file is opened the first time, initial cash balance is 5000
{
initial_bal = 5000;
ofstream write_cash_file("cash_bal_file.txt", ios::out);
write_cash_file << initial_bal; //writing the initial value of cash balance in cash_bal_file
write_cash_file.close();
read_cash_file.open("cash_bal_file.txt", ios_base::in);
read_cash_file >> cash_balance;
read_cash_file.close();
}
else //getting the latest cash balance
{
read_cash_file.open("cash_bal_file.txt", ios::in);
read_cash_file >> cash_balance;
read_cash_file.close();
}
}
else //case when the file could not be openend
cout << endl << "Sorry, cash_bal_file could not be opened." << endl;
}
double Account::getCashBal()
{
return cash_balance;
}
class BankAccount :public Account
{
public:
BankAccount();
void viewBalance();
};
BankAccount::BankAccount()
{
setCashBal();
cash_balance = getCashBal();
}
void BankAccount::viewBalance()
{
double balance;
ifstream view_bal("cash_bal_file.txt", ios_base::in); //getting the latest cash_balance from cash_bal_file.
view_bal >> balance;
cout << endl << "The balance in your bank account is " << balance << endl;
}
int main()
{
BankAccount bnkObj;
bnkObj.viewBalance();
return 0;
}