I am trying to get this program to start running but currently I just get errors. I am not sure how to get this to work. If I change the class SavingsAccount to public it should
You must declare an instance of the SavingsAccount class first. For example:
int main()
{
SavingsAccount account;
account.Information();
...
return 0;
}
Additionally, yes, the methods of the class that you want to call must be public.
You're trying to use member attributes inside your methods, yet you're trying to use your methods without an instance. All the member attributes' values are stored inside your instances, so you need an instance first. Add it into your main function:
int main(void)
{
SavingsAccount myAccount;
myAccount.Information();
myAccount.AccountClosureLoss();
myAccount.OutputInformation();
return 0;
}
Also your methods are defined to be private, you should always use public:
and private:
as following:
class SavingsAccount
{
public:
void Information();
inline double AccountClosureLoss()
{
return (accountBalance * accountClosurePenaltyPercent);
}
void OutputInformation();
private:
int accountType;
string ownerName;
long ssn;
double accountClosurePenaltyPercent;
double accountBalance;
};
You can't use methods without an instance. Even if you could (static maybe?) you can't use any member attributes inside them, so it'd be useless to include it into the class.
Since you cannot change the SavingsAccount class, and since it prohibits access to it's members (private
is the default), you are not supposed to use any menber of that class.
"The problem is in the main function": no, it is in the design of your class. A class with nothing public is not useful.
There is no clean solution to your problem.
A solution on the borderline of changing the class would be in defining an 'interface', and making the (unchanged) class inherit that interface:
class Account {
public:
virtual ~Account(){}
virtual void Information() = 0;
virtual double AccountClosureLoss() = 0;
virtual void OutputInformation() = 0;
};
class SavingsAccout : public Account {
... body remains unchanged
};
The main
will use Account
iso SavingsAccount
:
SavingsAccount savingsAccount;
Account& account = savingsAccount;
// should be accessible via the `Account` interface.
account.AccountClosureLoss();
Well by default member functions are private, so you can always add them into public as follows:
class SavingsAccount
{
private:
int accountType;
string ownerName;
long ssn;
public:
double accountClosurePenaltyPercent, accountBalance;
void Information();
inline double AccountClosureLoss()
{
return (accountBalance * accountClosurePenaltyPercent);
}
void OutputInformation();
};
You will now be able to call them from the main.