Wednesday, July 27, 2011

First Class


Here is a simple class. We divided the class into two files, the header that defines the class structure with its private and public members and a cpp file that actually implements the class methods.

First the header file: (Note: we have more fields--class variables--than we actually use)


BankAccount.h

#include

class BankAccount
{
private:
//private fields
int accountID;
std::string name;
double deposit;
double withdrawal;
double balance;
double initialBalance;
public:
//overloaded constuctors
BankAccount(int, double);
BankAccount(double);
BankAccount(int, std::string, double);

//Get methods for returning values
int GetAccountID();
std::string GetName();

double GetBalance();

//sets to change values
void SetAccountID(int);
void SetName(std::string);


//member functions
void AddDeposit(double);
void SubtractWithdrawal(double);



};



Here is the implementation:


BankAccount.cpp

#include "BankAccount.h"
#include
//constructors
BankAccount::BankAccount(double iBalance)
{
initialBalance=iBalance;
}

BankAccount::BankAccount(int accID, double iBalance)
{
initialBalance=iBalance;
balance=initialBalance;
SetAccountID(accID);
}

BankAccount::BankAccount(int accID, std::string name, double iBalance)
{
initialBalance=iBalance;
balance=initialBalance;
SetAccountID(accID);
SetName(name);
}

//gets
int BankAccount::GetAccountID()
{
return accountID;
initialBalance=0;
}

std::string BankAccount::GetName()
{
return name;
}



double BankAccount::GetBalance()
{
return balance;
}



//sets
void BankAccount::SetAccountID(int accID)
{
accountID=accID;
}



void BankAccount::SetName(std::string aName)
{
name=aName;
}

void BankAccount::AddDeposit(double depositAmt)
{
balance += depositAmt;
}

void BankAccount::SubtractWithdrawal(double withdrwl)
{
if (balance-withdrwl >=0)
{
balance-= withdrwl;
}

}



And here is the program file


Program.cpp

#include <iostream>
#include "BankAccount.h"
#include <string>

using namespace std;

int main()
{
string aName="Jones";
BankAccount account1(1,aName,1000);
account1.AddDeposit(500);
account1.AddDeposit(250.75);
account1.SubtractWithdrawal(225.43);

cout << "for account " << account1.GetAccountID() << "belonging to "
<< account1.GetName() << "the current balance is " << account1.GetBalance()
<< endl;


char c;
cin >> c;
}

No comments:

Post a Comment