bmb
bmb

Reputation: 401

Initializing enum class as null

I am wondering if it is possible to initialize an enum class as null. I have written up a short example to illustrate what I am asking about.

I have a header here that defines an enum class called ColorOptions

#ifndef COLORS_HPP
#define COLORS_HPP

enum class ColorOptions
{
  RED,
  BLUE
};
#endif

and I also have a class that is using this enum class to print colors based on the enum value

#include "Colors.hpp"
#include <iostream>

void printColor(ColorOptions col);

int main()
{
  printColor(ColorOptions::RED);
  printColor(ColorOptions::BLUE);
}

void printColor(ColorOptions col)
{
  switch(col)
  {
  case ColorOptions::RED:
    std::cout << "The color is red" << std::endl;
    break;
  case ColorOptions::BLUE:
    std::cout << "The color is blue" << std::endl;
    break;
  default:
    std::cout << "The color is unknown" << std::endl;
  }
}

Is it possible to initalize a ColorOptions as something other than RED or BLUE in this case? I want to reach the default case of the printColor method, but I am not sure if it is possible without adding another type to the ColorOptions enum.

Upvotes: 1

Views: 2082

Answers (1)

NathanOliver
NathanOliver

Reputation: 180500

The way to get a value not of the valid enumerations is to use static_cast. That would look like

printColor(static_cast<ColorOptions>(5));

and that will output

The color is unknown

If you can use C++17 then a nice thing you can do would be to change the enum to something like

enum class ColorOptions
{
  NONE,
  RED,
  BLUE
};

and then you can call your function like

printColor({});

which will give you an implicit value of NONE and cause The color is unknown to be print.

Upvotes: 5

Related Questions