Reputation: 1
I am new to StackOverflow and C++. I started to make a bank program but ran into a problem where the AddMoney()
function does not work in Tranfer()
function of class BankAccount
. I tried running it in main()
and there it works. I also tried to just directly add to the balance
variable and this also works. No errors are shown. Btw, Transfer()
function deducts money with DeductMoney()
(This func works btw) and then adds it to another account with AddMoney()
. Feedbacks appreciated on how to generally improve my code. Thanks in advance.
The Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <fstream>
using namespace std;
class BankAccount
{
string name;
int accno;
void DeductMoney(float);
void Transactions(BankAccount,float);
public:
// void AddMoney(float);
float balance;
BankAccount(string a,float b = 0)
{
name = a;
balance = b;
string var;
accno = rand();
/* for (int i;i<7;i++)
{
var += "rand() % 10";
};
accno = (int)var; */
}
void Transfer(BankAccount,float);
void Interest(float);
void Display(void)
{
cout << "Name of account: " << name << endl;
cout << "Balance: " << balance << endl;
};
};
/* void BankAccount :: AddMoney(float e)
{
//cout << "Money added " << e << endl;
//cout << "Adding Money to accno: " << accno << endl;
balance += e;
} */
void BankAccount :: DeductMoney(float b)
{
balance -= b;
cout << "Deducting money from accno: " << accno << endl;
}
void BankAccount :: Transfer(BankAccount a,float b)
{
cout << "Transfering..." << endl;
this->DeductMoney(b);
a.balance += b;
this->Transactions(a,b);
a.balance += b;
}
void BankAccount :: Interest(float intrst = 0.18)
{
balance += balance * intrst;
cout << "Interst added: " << balance*intrst << endl;
}
void BankAccount :: Transactions(BankAccount a,float b)
{
cout << name << " transferred " << b << " to " << a.name << endl;
}
main()
{
BankAccount C1("Abcd",100.0);
BankAccount B2("Degf",200.0);
//C1.AddMoney(50.0);
B2.Transfer(C1,50.0);
C1.Display();
B2.Display();
return 0;
}
Upvotes: 0
Views: 280
Reputation: 75062
In this function:
void BankAccount :: Transfer(BankAccount a,float b)
The a
parameter is a copy of what is passed to it, so modifications to that copy will not affect the original that is passed in.
If the modifications should apply to the original, you should add &
after BankAccount
(for both declaration and definition) to make it a reference.
void BankAccount :: Transfer(BankAccount& a,float b)
Upvotes: 2