Anda di halaman 1dari 3

Adt.

#ifndef ADT_H
#define ADT_H

namespace Banking
{
class InsufficientFunds{};

class Account
{
public:
Account();
int Id() const;
double Balance() const;
virtual void Deposit(double) = 0;
virtual void Withdraw(double) throw (InsufficientFunds) = 0;
void Transfer(double, Account*) throw (InsufficientFunds);
virtual ~Account(){};
protected:
double balance;
private:
int id;
friend Account* OpenAccount(double, bool);
};

class SavingsAccount : public Account


{
public:
SavingsAccount();
void Deposit(double);
void Withdraw(double) throw (InsufficientFunds);
double AddInterest(short=1);
};

class CurrentAccount : public Account


{
public:
void Deposit(double);
void Withdraw(double) throw (InsufficientFunds);
};

Account* OpenAccount(double, bool);


void CloseAccount(Account*);
}

#endif

Adt.cpp

#include "adt.h"
#include <ctime>

namespace Banking
{
Account::Account()
{
id = 0;
balance = 0;
}

int Account::Id() const


{
return id;
}

double Account::Balance() const


{
return balance;
}

void Account::Transfer(double amount, Account* other)


throw (InsufficientFunds)
{
if(other != this)
{
this->Withdraw(amount);
other->Deposit(amount);
}
}

SavingsAccount::SavingsAccount()
{
balance = 5000;
}

void SavingsAccount::Deposit(double amount)


{
balance += amount;
}

void SavingsAccount::Withdraw(double amount) throw (InsufficientFunds)


{
if(balance - amount < 5000)
throw InsufficientFunds();

balance -= amount;
}

double SavingsAccount::AddInterest(short period)


{
float rate = balance < 10000 ? 5.5 : 6.0;
double interest = balance * period * rate / 100;

balance += interest;

return interest;
}

void CurrentAccount::Deposit(double amount)


{
if(balance < 0)
amount *= 0.9;

balance += amount;
}

void CurrentAccount::Withdraw(double amount) throw (InsufficientFunds)


{
balance -= amount;
}
Account* OpenAccount(double amount, bool savings)
{
static int nextid = time(0) % 1000000;
Account* acc;

if(savings)
acc = new SavingsAccount;
else
acc = new CurrentAccount;

acc->id = nextid++;
acc->Deposit(amount);

return acc;
}

void CloseAccount(Account* acc)


{
delete acc;
}
}

Adttest.cpp

#include "adt.h"
#include <iostream>

using namespace std;

int main(void)
{
using namespace Banking;

Account* cust = OpenAccount(4000, true);


Account* vend = OpenAccount(3000, false);

double amt;
cout << "Amount to transfer: ";
cin >> amt;

try
{
cust->Transfer(amt, vend);
cout << "Transfer succeeded." << endl;
}
catch(InsufficientFunds)
{
cout << "Transfer failed due to lack of funds! " << endl;
}

cout << "Customer Account ID is " << cust->Id()


<< " and Balance is " << cust->Balance() << endl;
cout << "Vendor Account ID is " << vend->Id()
<< " and Balance is " << vend->Balance() << endl;

CloseAccount(vend);
CloseAccount(cust);
}

Anda mungkin juga menyukai