Reputation: 4659
I am trying to figure out my mistake.
I am working on Account
class in C++, where there are a few methods like credit()
, debit()
, etc.
I wrote a transfer()
method and the problem I get is that it takes "money" out of account a1
but does not credit the a2
. However if I print it within the method itself in account.cpp it does show the correct result, while in main the balance stays the same.
Can you see my mistake? Something to do with reference, pointers, etc?
Here is the main:
a1.println();
a2.println();
cout<< "Valid parameter " << endl;
cout<< a1.transfer(a2, 13) << endl;
a1.println();
a2.println();
Here is what it prints:
(Account(65,140))
(Account(130,100))
Valid parameter
1
(Account(65,127))
(Account(130,100))
Here is the definition of methods:
// withdraw money from account
bool Account::debit(int amount){
if (amount>=0 && balance>=amount) {
balance=balance-amount; // new balance
return true;
} else {
return false;
}
}
// deposit money
bool Account::credit(int amount){
if (amount>=0) {
balance=balance+amount; // new balance
return true;
} else {
return false;
}
}
bool Account::transfer(Account other, int amount){
if (amount>=0 && balance>=amount) {
debit(amount);
other.credit(amount);
//other.println();// prints corect amount
return true;
} else {
return false;
}
}
Upvotes: 1
Views: 103
Reputation: 6882
You did not pass "other" by reference
bool Account::transfer(Account& other, int amount){
Upvotes: 1
Reputation: 726599
This is because you are passing the other Account
by value. The balance gets changed OK, but on a different instance of the account, meaning that the copy gets modified, while the original stays intact.
Change your code to passing Account
by reference to make it work.
bool Account::transfer(Account& other, int amount)
// ^
// HERE
Upvotes: 7