// File "NestMain.cc, by KWR for CSE250, Spr'00. Goes with NestPack/ // Illustrates nested "interfaces" in C++. // All classes are put in the same file for simplicity. #include #include class BST { public: class Sortable { public: virtual bool lessThan(Sortable* rhs) const = 0; virtual bool lteq(Sortable* rhs) const = 0; virtual int compare(Sortable* rhs) const = 0; // returns -1 for <, 0 for ==, +1 for > }; }; class MySortableItem : public BST::Sortable { string key; public: virtual bool lessThan(BST::Sortable* rhs) const { return key < ((MySortableItem*)rhs)->key; } virtual bool lteq(BST::Sortable* rhs) const { return key <= ((MySortableItem*)rhs)->key; } virtual int compare(BST::Sortable* rhs) const { return key.compare(((MySortableItem*)rhs)->key); } MySortableItem() {} }; int main() { MySortableItem* ii = new MySortableItem(); if (ii->compare(ii) != 0) { cout << "Something is weird!" << endl; } else { cout << "Compiles and runs OK." << endl; } } // Try running this forgetting to put in the *s after "Sortable", and // see what error messages you get! C++ will think you want a // parameter of an abstract class by-value, which is impossible, but // C++ will let you have a pointer to the abstract class as a parameter. // LIKEWISE, try forgetting the *s after MySortableItem in the promotion // casts! I fell into that one, out of familiarity with Java!