I finished creating a - very noob, because I'm still a noob :( - program that acts as a bank account.
I have main.cpp, Account.cpp, Account.h.
In main.cpp I have:
#include <iostream>
#include <string>
#include "Account.h"
int main()
{
Account Luigis;
Luigis.set_name("Luigi's Account");
Luigis.set_balance(0);
std::string letter;
do {
std::cout << "Your current balance is: " << Luigis.get_balance() << std::endl;
std::cout << "What would you like, to deposit, to withdraw or to exit?" << std::endl;
std::cout << "(D for 'Deposit, W for 'Withdraw' and Q for 'Exit') D/W/Q ";
std::cin >> letter;
if(letter == "d" || letter == "D") {
std::cout << "How much would you like to deposit?: ";
double amountDeposit{};
std::cin >> amountDeposit;
Luigis.deposit(amountDeposit);
}
else if(letter == "w" || letter == "W") {
std::cout << "How much would you like to withdraw?: ";
double amountWithdraw;
std::cin >> amountWithdraw;
Luigis.withdraw(amountWithdraw);
}
else if(letter == "q" || letter == "Q") {
std::cout << "Goodbye!" << std::endl;
}
else
std::cout << "Invalid selection, please try again with: D for Deposit, W for Withdraw, Q for Exist" << std::endl;
} while (letter != "q" && letter != "Q");
return 0;
}
In Account.cpp I have:
#include "Account.h"
#include <string>
#include <iostream>
//IMPLEMENTATION or DEFINITION
bool Account::deposit(double amount) {
//money you're doing to deposit
balance = balance + amount;
}
bool Account::withdraw(double amount) {
//if you can withdraw
if(balance-amount >= 0) {
balance = balance - amount;
return true;
} else {
std::cout << "You cannot withdraw the specified amount - balance is too low and it would result in " << balance - amount << " funds!" << std::endl;
return false;
}
}
void Account::set_name(std::string name) {
this->name = name;
}
std::string Account::get_name(){
return name;
}
void Account::set_balance(double balance) {
this->balance = balance;
}
double Account::get_balance() {
return balance;
}
And in Account.h I have:
#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_
#include <string>
//SPECIFICATION or DECLARATION
class Account
{
private:
//attributes
std::string name;
double balance;
public:
//methods
bool deposit(double amount);
bool withdraw(double amount);
void set_name(std::string name);
std::string get_name();
void set_balance(double balance);
double get_balance();
};
#endif // _ACCOUNT_H_
My question is: how can I simplify the if-else statements in main.cpp now that I "know" how to use functions? My friend said that I should be able to use functions and make things more abstract to avoid writing all the if and else statements.
Basically I'm mixing OOP with Procedural Programming, and that defeats the purpose.