



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




#include
// Note we’ve inlined all the functions (even though some are > 1 line of code)
// ------------------------------------------------------------------------------- class Account { public: Account(double bal = 0.0) : balance(bal) {} void deposit(double amt) { balance += amt; } double get_balance() const { return balance; }
protected: double balance; // account balance };
// ------------------------------------------------------------------------------- class SavingsAccount : public Account { public: SavingsAccount(double bal = 0.0, double pct = 5.0) : Account(bal), rate(pct/100.0) {}
double compound() { // computes and deposits interest double interest = balance * rate; balance += interest; return interest; } double withdraw(double amt) { // if overdraft ==> return 0, else return amount if (amt > balance) { return 0.0; } else { balance -= amt; return amt; } }
protected: double rate; // periodic interest rate };
// ------------------------------------------------------------------------------- class CheckingAccount : public Account { public: CheckingAccount(double bal = 0.0, double lim = 500.0, double chg = 0.5) : Account(bal) { limit = lim; charge = chg; }
double cash_check(double amt) { assert (amt > 0); if (balance < limit && (amt + charge <= balance)) { balance -= amt + charge; return amt + charge; } else if (balance >= limit && amt <= balance) { balance -= amt; return amt; } else { return 0.0; } }
protected: double limit; // lower limit for free checking double charge; // per check charge };
template
Create a class hierarchy of geometric objects, such as: triangle, isosceles triangle, right triangle, quadrilateral, square, rhombus, kite, trapezoid, circle, ellipse, etc. How should this hierarchy be arranged? What member variables and member functions should be in each class?
class Polygon { public: Polygon() {} virtual ~Polygon() {} int NumVerts() { return verts.size(); } virtual double Area() = 0; virtual bool IsSquare() { return false; } protected: vector
class Triangle : public Polygon { public: Triangle(Point pts[3]) { for (int i = 0; i < 3; i++) verts.push_back(pts[i]); } double Area(); };
class Quadrilateral : public Polygon { public: Quadrilateral(Point pts[4]) { for (int i = 0; i < 4; i++) verts.push_back(pts[i]); } double Area(); double LongerDiagonal(); bool IsSquare() { return (SidesEqual() && AnglesEqual()); } private: bool SidesEqual(); bool AnglesEqual(); };
std::list<Polygon*> polygons;
Polygon *p_ptr = new Triangle( .... ); polygons.push_back(p_ptr); p_ptr = new Quadrilateral( ... ); polygons.push_back(p_ptr); Triangle *t_ptr = new Triangle( .... ); polygons.push_back(t_ptr);
Note: We’ve used the same pointer variable (p ptr) to point to objects of two different types.