Error constructing temporary object whose constructor takes a single enum parameter

110 views Asked by At

Why is the below code invalid (at least using Visual Studio 2010 or ideone)?

// E.h
enum E
{
  AN_E_VALUE
};

// C.h
class C
{
public:
  explicit C(E e) // explicit keyword is optional
  {}

  void Foo() {}
};

// main.cpp
int main(int argc, char** argv)
{
  C c(AN_E_VALUE);      // fine
  C(AN_E_VALUE);        // error
  C(AN_E_VALUE).Foo();  // fine
  return 0;
}

If the parameter is anything but a single enumerated type, it works fine.

The compiler understands the erroneous call as one with 0 arguments where 1 is expected. Why is this?

1

There are 1 answers

2
Columbo On BEST ANSWER
C(AN_E_VALUE);

This declares an object of type C with name AN_E_VALUE. The error complains about the fact that you need a default constructor to initialize AN_E_VALUE, but no default constructor exists (and none is implicitly declared).
Have you ever tried this?:

int(a);

That's essentially accomplishes the same thing. Perhaps check out this question.