Hi all. I'm perplexed. I have an array of pointers to Account objects. In the Account object, there's a private data member- float money. I'm trying to add to money, but for some reason it wont keep its value outside of the add_money() function.
basic mainline:
Code:
#include "ActList.h"
int main()
{
ActList newList;
newList.add_account(0);
newList.get_account(0).add_money();
newList.display_account(0);
return(0);
}
ActList:
Code:
//ActList.h
#ifndef actlist_h
#define actlist_h
#include "Account.h"
const int MAX_NUM_ACTS = 20;
class ActList
{
public:
ActList();
void add_account(int);
void remove_account(int);
void display_account(int);
int find_account(std::string);
Account get_account(int num){return(*actAry[num]);};
private:
int numActs;
Account *actAry[MAX_NUM_ACTS];
};
#endif
//ActList.cpp
#include "ActList.h"
ActList::ActList()
{
numActs = 0;
};
void ActList::add_account(int num)
{
Account * ptrAcct;
if(num == 1)
{
ptrAcct = new Savings;
}
else
{
ptrAcct = new Account;
}
actAry[numActs] = ptrAcct;
numActs++;
return;
};
int ActList::find_account(std::string nameToFind)
{
for(int i = 0; i < numActs; i++)
{
if(nameToFind == actAry[i]->get_name())
{
return(i);
}
}
return(-1);
};
void ActList::display_account(int num)
{
std::cout << "Account name: " << actAry[num]->get_name() << std::endl;
std::cout << "Account Balance: " << actAry[num]->get_money() << std::endl;
return;
};
Account class:
Code:
#ifndef account_h
#define account_h
#include <string>
#include <iostream>
class Account
{
public:
Account();
void add_money();
void remove_money();
float get_money(){return(money);};
std::string get_name(){return(name);};
void set_name();
void display();
virtual float calc_interest(){return(0);}
virtual void add_interest(){}
virtual void set_intrate(){}
protected:
float money;
std::string name;
};
#endif
//Account.cpp
#include "Account.h"
Account::Account()
{
money = 0;
set_name();
};
void Account::add_money()
{
float numToAdd;
std::cout << money <<"\n";
do
{
std::cout << "How much would you like to add? ";
std::cin >> numToAdd;
}while(numToAdd < 0);
money += numToAdd;
//it's correct here!
std::cout << money << "\n";
return;
};
void Account::remove_money()
{
int numToRemove;
do
{
std::cout << "How much would you like to remove? ";
std::cin >> numToRemove;
}while(numToRemove < 0 || numToRemove > money);
money -= numToRemove;
};
void Account::set_name()
{
std::cout << "What would you like to name this account? ";
std::cin >> name;
};
void Account::display()
{
std::cout << "Account name: " << name << std::endl;
std::cout << "Account balance: $" << money << std::endl;
};
I'm baffled as to why it wont add to money outside of that function. Does anybody have any idea of what's going on here? It's probably gonna be something simple and I'll feel embarassed, but I've been working on this one problem for like 2 hours now.