home *** CD-ROM | disk | FTP | other *** search
- #include <iostream.h>
-
- // Some miscellaneous definitions we will need
- typedef enum {
- WHOLE,
- SHREDDED,
- GRATED,
- SLICED,
- CHOPPED
- } FoodState;
-
- // The top of the inheritance tree
- class Food {
- public:
- // Constructor
- Food(const FoodState = WHOLE);
-
- // Virtual methods - all food
- // must be able to set and return
- // its state. These functions also
- // ensure that Food is polymorphic
- // and can use RTTI.
- virtual FoodState GetState() const;
- virtual void SetState(const FoodState);
-
- private:
- // Private member data
- FoodState theFoodState;
- };
-
- // Food constructor
- Food::Food(const FoodState newState)
- {
- SetState(newState);
- }
-
- // Getter and setter virtual methods
- FoodState Food::GetState() const
- {
- return theFoodState;
- }
-
- void Food::SetState(const FoodState newState)
- {
- theFoodState = newState;
- }
-
- // Overload << so we can display our state
- ostream& operator<<(ostream& outstrm,
- Food& theFood)
- {
- switch(theFood.GetState()) {
- case WHOLE: outstrm << "Whole";
- break;
- case SHREDDED: outstrm << "Shredded";
- break;
- case GRATED: outstrm << "Grated";
- break;
- case SLICED: outstrm << "Sliced";
- break;
- case CHOPPED: outstrm << "Chopped";
- break;
- default:
- outstrm << "Bad state!";
- }
- return outstrm;
- }
-
-
- // Intermediate class grouping
- class SaladIngredient : public Food {
- public:
- // Pure virtual function which any
- // salad ingredient class must
- // provide
- virtual void ProcessIngredient() = 0;
- };
-
-
- // Individual food types
- class Apple : public SaladIngredient {
- public:
- void ProcessIngredient() { SetState(CHOPPED); }
- };
-
- class Cheese : public Food {
- public:
- void ProcessIngredient() { SetState(GRATED); }
- };
-
- class Lettuce : public Food {
- public:
- void ProcessIngredient() { SetState(SHREDDED); }
- };
-
-
- // LetÆs prepare a salad
- void main()
- {
- Lettuce MyLettuce;
- Apple MyApple;
- Cheese MyCheese;
-
- // Process the vegetables
- MyLettuce.ProcessIngredient();
- MyApple.ProcessIngredient();
- MyCheese.ProcessIngredient();
-
- // Show what weÆve done
- cout << "The lettuce is ";
- cout << MyLettuce << "\n";
- cout << "The apple is ";
- cout << MyApple << "\n";
- cout << "The cheese is ";
- cout << MyCheese << "\n";
- }
-