I would say the logic could be broken up. Your class does the job of both the bank and the bank account.
You could have a class to handle just the Bank logic and a class to handle the BankAccount logic. Then your Bank can store accounts and act as an intermediary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class BankAccount
{
public:
BankAccount() = default;
~BankAccount() = default;
int GetBalance();
bool Withdraw(int Amount);
void Desposit(int Amount);
bool CheckCredentials(const std::string &NameEntered, int PinEntered);
private:
std::string ownerName = "Default";
int accountNumber = 0;
int currentBalance = 0;
int accountPin = 0;
int holderAge = 0;
};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Bank
{
public:
Bank() = default;
~Bank() = default;
void MainMenu();
private:
bool CreateNewAccount();
bool AccessAccount();
//And some variable to store the accounts
std::map<int, BankAccount> accounts;
};
|
That examples ignores all security best-practices, but it's illustrative.
However, this
is now a good chance for you to use a constructor to set some value for the BankAccount's data. If you want some piece of data to be immutable (the account number, for example), you could pass the value entered by the user to the constructor and make the BankAccount's member variable for it be const-qualified so it can never be changed.
Like
1 2 3 4 5 6 7 8
|
bool Bank::CreateAccount()
{
int acctNumber = 0;
//generate some account number
//get info from user, etc
accounts[acctNumber] = BankAccount(NameEntered, PinEntered, acctNumber);
...
}
|
Then BankAccount would have a constructor that takes a string and two ints that sets its members appropriately.
I try to make my code do what i want in as little code as possible if i know how/spot the problem. |
That's generally a good idea. However, shorter code isn't always easier to read, and making it a little longer can make it more readable.
Take, for example:
This piece of short code:
1 2 3
|
string slurp(ifstream& in) {
return static_cast<stringstream const&>(stringstream() << in.rdbuf()).str();
}
|
vs this longer piece:
1 2 3 4 5
|
string slurp(ifstream& in) {
stringstream sstr;
sstr << in.rdbuf();
return sstr.str();
}
|
(from
https://stackoverflow.com/questions/116038/what-is-the-best-way-to-read-an-entire-file-into-a-stdstring-in-c?noredirect=1&lq=1)
They both do the same thing, but I'd argue the latter is easier to look at and understand quickly.
Using it to initalize every single variable when it can just be done at its declaration point just seems like a waste of time and whitespace, but maybe thats just me. |
Well, the less code clutter the better, and the more explicit the better; the two will make it easier for other to understand your code (or you yourself if you come back to it later and have forgotten its purpose/design).
Polymorphism is where I think C++ truly shines. Plenty of languages have class inheritance, but I've yet to encounter any that really leverage it like C++ does.