Thursday, July 1, 2010

C++ enum default constructor

Every C++ enumeration type has a default constructor. Suppose we have the following enum specifier:
enum thing {
  foo = 13, bar = 31,
what would the following program print? The answer may be surprising.
#include <iostream>

int main() {
  thing x = thing();  // invokes enum's default constructor.
  std::cout << "x = " << x << std::endl;
  return 0;
It turns out that the code above will print x = 0, which is the integer value of neither foo nor bar. The reason is that enum is considered plain old data (ISO/IEC 14882 2003 section 3.9 clause 10), and all POD type have default initializer that initializes the value to zero (ISO/IEC 14882 2003 section 8.5 clause 5).

When dealing with an enum type value, we must always consider the possibility of 0 even if it was not one of our declared choices.

No comments: