C++ Enum Inheritance Example

#include "stdio.h"
 
// "Base" enum defining three colors.
 
enum Color
{
   Red = 0,
   Blue,
   Green,
   LastColor,
   FinalColor = 65535
};
 
// Object for displaying the Color enum.
 
class ColorPrinter
{
public:
   virtual void printColor(Color color);
};
 
void
ColorPrinter::printColor(Color color)
{
   switch (color)
   {
      case Color::Red:
         printf("Red");
         break;
      case Color::Blue:
         printf("Blue");
         break;
      case Color::Green:
         printf("Green");
         break;
      default:
         printf("Unknown");
         break;
   }
}
 
// "Derived" enum defining pastels.
// Note the use of Color::LastColor to pick up the enumeration where
// Color left off.
// Similarly define LastPastel for an enum to extend Pastel.
 
enum Pastel
{
   Turqoise = Color::LastColor,
   Lavender,
   Peach,
   LastPastel,
};
 
// Object for displaying the Pastel enum.
 
class PastelColorPrinter : public ColorPrinter
{
public:
   virtual void printColor(Color color);
   void printColor(Pastel pastel);
};
 
// Override for Color type, defer to Pastel implementation.
 
void
PastelColorPrinter::printColor(Color color)
{
   this->printColor((Pastel)color);
}
 
void
PastelColorPrinter::printColor(Pastel pastel)
{
   switch (pastel)
   {
      case Pastel::Turqoise:
         printf("Turqoise");
         break;
      case Pastel::Lavender:
         printf("Lavender");
         break;
      case Pastel::Peach:
         printf("Peach");
         break;
      default:
         if (pastel < Color::LastColor)
         {
            // An enum is just an integer so we can check the range.
            // Defer to base implementation of printColor.
 
            ColorPrinter::printColor((Color)pastel);
         }
         else
         {
            printf("Unknown");
         }
         break;
   }
}
 
// Example class which demonstrates using Color with no direct
// knowledge of Pastel.
 
class Designer
{
public:
   void displayPreference(Color color);
   void installColorPrinter(ColorPrinter * colorPrinter);
private:
   ColorPrinter * colorPrinter;
};
 
void
Designer::displayPreference(Color color)
{
   printf("I like ");
   colorPrinter->printColor(color);
   printf("\n");
}
 
void
Designer::installColorPrinter(ColorPrinter * colorPrinter)
{
   this->colorPrinter = colorPrinter;
}
 
// Demonstrate use of Designer.
 
int main()
{
   PastelColorPrinter pastelColorPrinter = PastelColorPrinter();
 
   Designer designer = Designer();
   designer.installColorPrinter(&pastelColorPrinter);
 
   designer.displayPreference(Color::Red);
   designer.displayPreference((Color)Pastel::Lavender);
 
   return 0;
}
random/c_enum_inheritance.txt · Last modified: 2013/04/26 22:16 by grant