home *** CD-ROM | disk | FTP | other *** search
- // Chap24_1.cpp - notice that this program should die
- // a miserable death; see main() for details
- #include <iostream.h>
- #include <iomanip.h>
- class USDollar
- {
- public:
- USDollar(double v = 0.0)
- {
- dollars = v;
- cents = int((v - dollars) * 100.0 + 0.5);
- signature = 0x1234; //itÆs a valid object now
- }
- ~USDollar()
- {
- if (isLegal("destructor"))
- {
- signature = 0; //itÆs no longer a valid object
- }
- }
- operator double()
- {
- if (isLegal("double"))
- {
- return dollars + cents / 100.0;
- }
- else
- {
- return 0.0;
- }
- }
- void display(ostream& out)
- {
- if (isLegal("display"))
- {
- out << '$' << dollars << '.'
- << setfill('0') << setw(2) << cents
- << setfill(' ');
- }
- }
- int isLegal(char *pFunc);
- protected:
- unsigned int signature;
- unsigned int dollars;
- unsigned int cents;
- };
- //isLegal - check the signature field. If it doesnÆt
- // check out, generate error and return indicator
- int USDollar::isLegal(char *pFunc)
- {
- if (signature != 0x1234)
- {
- cerr << "\nInvalid USDollar object address passed to "
- << pFunc
- << "\n";
- return 0;
- }
- return 1;
- }
- ostream& operator<< (ostream& o, USDollar& d)
- {
- d.display(o);
- return o;
- }
-
- void printSalesTax(USDollar &amount)
- {
- cout << "Tax on "
- << amount
- << " = "
- << USDollar(0.0825 * amount)
- << "\n";
- }
- int main()
- {
- cout << "First case\n";
- USDollar usd(1.50);
- printSalesTax(usd);
- cout << "\n";
-
- // this case should cause the program to crash since
- // pUSD is not initialized to a legal object
- cout << "Second case\n";
- USDollar *pUSD;
- printSalesTax(*pUSD);
- return 0;
- }
-