// This code demonstrates polymorphism. foo() doesn’t know what // particular sort of Readable it’s dealing with, but it calls // methods whose implementations vary amongst the derived classes. // // The oi() method is just there to make it harder. #include #include using namespace std; // Something you can read. Could be a comic book, a billboard, // a computer display, etc. class Readable { public: virtual void oi() const { cout << "Hello there!\n"; } virtual int power_consumption() const = 0; // mW/hour virtual float cost() const = 0; // U.S. Dollars }; void foo(const Readable &thing) { thing.oi(); cout << fixed << setprecision(2) << "This thing costs $" << thing.cost() << " and consumes " << thing.power_consumption() << " mW/h\n"; } // This code might be in a whole different file: class Book : public Readable { public: virtual int power_consumption() const override { return 0; } virtual float cost() const override { return 3.00; } }; // Remember that override is optional, and virtual is inherited. class Ipad : public Readable { public: int power_consumption() const { return 17; } // I made this up. float cost() const { return 219.99; } // Amazon.com, refurb }; int main() { Book b; Ipad i; foo(b); foo(i); }