I've developed a compiling bank system of different accounts. My base class is Account, and derived classes are Checking, Savings, MoneyMarket. The latter three inherit private member variable 'balance' from Account. All four accounts need to maintain and modify their own 'balance'.
However, I'm confused about the relation between Account's balance and derived class's 'balance'.
As you can see in Checking's getBalance(), it is forced to use Account's getBalance() due to the private variable, and the code only works when it displays Account::balance. This seems very strange, that it should call Account's balance to display it's own.
Please note that that all of Account's public methods are virtual to allow override.
Why does this work the way it is? Shouldn't the derived classes call their own copy of 'balance'?
Note: this code works and correctly displays the exact modified balance for each object. Below is Checking.cpp:
#include <iostream>
#include <iomanip>
#include "Checking.h"
using namespace std;
Checking::Checking() {setBalance(500); }
Checking::~Checking() {setBalance(0);}
void Checking::Withdrawal(double p_withdrawal){
setBalance( getBalance(0) - p_withdrawal);
cout << setprecision(2) << fixed;
cout<<"\nWithdrawal from Checking leaves balance: "<<getBalance(0);
}
double Checking::getBalance(bool print){
if (print==1)
cout<<"\nBalance of Checking:"<< Account::getBalance(0);
return Account::getBalance(1);
}
And for Account.h:
#ifndef ACCOUNT_H
#define ACCOUNT_H
using namespace std;
class Account{
public:
Account();
~Account();
virtual double getBalance(bool);
virtual void setBalance(double);
virtual void Deposit(double);
virtual void Withdrawal(double);
virtual void Transfer(Account&, Account&, double);
private:
double balance;
};
#endif