// VirtualInserter - base USDollar on the base class // Currency. Make the inserter virtual // by having it rely on a virtual // display() routine #include #include #include // Currency - represent any currency class Currency { friend ostream& operator<<(ostream& out, Currency& d); public: Currency(int p = 0, int s = 0) { nPrimary = p; nSecondary = s; } // rationalize - normalize the number of nCents by // adding a dollar for every 100 nCents void rationalize() { nPrimary += (nSecondary / 100); nSecondary %= 100; } // display - display the object to the // given ostream object virtual ostream& display(ostream&) = 0; protected: int nPrimary; int nSecondary; }; // inserter - output a string description // (this version handles the case of cents // less than 10) ostream& operator<<(ostream& out, Currency& c) { return c.display(out); } // define dollar to be a subclass of currency class USDollar : public Currency { public: USDollar(int d, int c) : Currency(d, c) { } // supply the display routine virtual ostream& display(ostream& out) { char old = out.fill(); out << "$" << nPrimary << "." << setfill('0') << setw(2) << nSecondary; // replace the old fill character out.fill(old); return out; } }; void fn(Currency& c, char* pszDescriptor) { cout << pszDescriptor << c << "\n"; } int main(int nArgc, char* pszArgs[]) { // invoke USDollar::display() directly USDollar d1(1, 60); cout << "d1 = " << d1 << "\n"; // invoke the same function virtually // through the fn() function USDollar d2(1, 5); fn(d2, "d2 = "); return 0; }