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;
- }
-
-
- // Individual food types
- class Apple : public Food {
- public:
- void Chop() { SetState(CHOPPED); }
- void Slice() { SetState(SLICED); }
- };
-
- class Cheese : public Food {
- public:
- void Grate() { SetState(GRATED); }
- };
-
- class Lettuce : public Food {
- public:
- void Shred() { SetState(SHREDDED); }
- };
-
-
- // Process a single ingredient
- void ProcessIngredient(Food* pIngredient)
- {
- // Is this an Apple?
- Apple* pApple =
- dynamic_cast<Apple*>(pIngredient);
- if (pApple) {
- pApple->Chop();
- return;
- }
-
- // Is this a head of Lettuce?
- Lettuce* pLettuce =
- dynamic_cast<Lettuce*>(pIngredient);
- if (pLettuce) {
- pLettuce->Shred();
- return;
- }
-
- // Is this a piece of Cheese?
- Cheese* pCheese =
- dynamic_cast<Cheese*>(pIngredient);
- if (pCheese)
- pCheese->Grate();
-
- return;
- }
-
- // LetÆs prepare a salad
- void main()
- {
- Lettuce MyLettuce;
- Apple MyApple;
- Cheese MyCheese;
-
- // Process the vegetables
- ProcessIngredient(&MyLettuce);
- ProcessIngredient(&MyApple);
- ProcessIngredient(&MyCheese);
-
- // 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";
- }
-