I know it's such a basic question, but I am just blinded..
I have a class Account, then a class AccountList that contains an array of type Account, then class Bank that contains AccountList.
in class Account there is a method int get_balance() ,
in class Bank I need to implement a method int total_balance(),
which will add all balances of Accounts that are in the AccountList.
I understand I should run a 'for-loop' through the list and call get_balance() and add them up +=, but I am confused about the actual syntax. I can call methods one level lower no problem though.. any suggestions? Thanks.
this is what i tried and obviously it's wrong
1 2 3 4 5 6 7 8 9 10 11
int Bank::total_balance(){
int totalBalance;
for (int i = 0; i<accountList.size(); i++) {
totalBalance += accountList.get(i).get_balance();
}
return totalBalance;
}
here are the declarations of my classes:
Account.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Account {
int account_number;
int balance;
public:
Account();
Account(int anr, int b);
int get_account_number();
void set_account_number(int anr);
int get_balance();
bool set_balance(int b);
bool debit(int amount);
bool credit(int amount);
bool transfer(Account& other, int amount);
void print();
void println();
};
AccountList.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class AccountList {
Account aList[3]; //
int sz;
int capacity;
public:
AccountList();
bool add(Account& a);
Account get(int i);
int size();
Account remove(int i);
int find(int anr);
void println();
};
Bank.h
1 2 3 4 5 6 7 8 9 10 11 12 13
class Bank {
AccountList accountList;
public:
Bank();
bool add_aacount(Account& a);
bool remove_account(int i);
int total_balance();
void print();
void println();
};
I thought it automatically initializes to 0, but yes, c++ is nasty with these things. Thanks. However my problem persists. It returns a 0 all the time. If i call get_balance() of class Account in main, it returns correctly. But in Bank.cpp wont do it.
Alright! I see my mistake now. I had a silly assumption that since Bank contained AccountList, everything would be in the Bank too. But then why would I need add_account() in the Bank.. Thank you guys!