I need help with writing the main() Nothing is working for me. I have to provide
ID: 3589633 • Letter: I
Question
I need help with writing the main()
Nothing is working for me.
I have to provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it’s greater than or equal to 0. If not, set the balance to 0 and display an error message indicating that the initial balance was invalid.
(I cant even create my objects in the main(). ) -- creates two Account objects and tests the member functions of class Account.
What am I doing wrong??
#include <iostream>
using namespace std;
class Account {
private:
double balance; // double type data member for balance
public:
// constructor
Account(double initialB) {
if (initialB < 0)
{
cout << "ERROR: initial balance was invald." << endl;
}
else
{
balance = 0;
}
}
void credit(double c)
{
balance += c;
}
void debit(double d)
{
if (balance - d < 0)
{
cout << "Debit amount exceeded account balance." << endl;
}
else
{
balance -= d;
cout << "Withdraw: $" << d << endl;
}
}
double getBalance()
{
return balance;
}
};
int main() {
}
Explanation / Answer
Hi,
I have modified the code and highlighted the code change below
#include <iostream>
#include <iomanip>
using namespace std;
class Account {
private:
double balance; // double type data member for balance
public:
// constructor
Account ( double initialB ) {
if (initialB < 0)
{
cout << "ERROR: initial balance was invald." << endl;
}
else
{
balance = initialB;
}
}
void credit(double c)
{
balance += c;
}
void debit(double d)
{
if (balance - d < 0)
{
cout << "Debit amount exceeded account balance." << endl;
}
else
{
balance -= d;
cout << "Withdraw: $" << d << endl;
}
}
double getBalance()
{
return balance;
}
};
int main() {
// I am tring to decalre an object like this
// Please help me out! Im not sure where to go with testing my member function in the main??
Account a1(1000), a2(500);
a1.credit(100);
a1.debit(150);
cout<<"Account a1 balance: "<<a1.getBalance()<<endl;
a2.credit(100);
a2.debit(150);
cout<<"Account a2 balance: "<<a2.getBalance()<<endl;
}
Output: