C++ Classes and Objects How can I implement this in the main()? --Create a progr
ID: 3589512 • Letter: C
Question
C++ Classes and Objects
How can I implement this in the main()?
--Create a program that creates two Account objects and tests the member functions of class Account.
How can I implement this in the main()?
Here is what I have so far:
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() {
// 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;
a1.credit(100);
}
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:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.