Still not why you couldn't just assign it though, and why you need to use a cast instead
You can assign it 0 in C without a cast, but the C++ type system is more restrictive so that things like function overloading (which doesn't exist in C) work properly. Also, if you can easily assign an integer to a Weekday type you can easily assign an incorrect value, i.e., one that doesn't have a constant name defined. It's best to assign one of the constants directly.
Code:
#include <iostream>
enum Weekday { Sunday, Monday, Tuesday };
void print(Weekday d) {
using std::cout;
cout << "Weekday: ";
switch (d) {
case Sunday: cout << "Sunday"; break;
case Monday: cout << "Monday"; break;
case Tuesday: cout << "Tuesday"; break;
}
cout << '\n';
}
// Same function name, different argument type
void print(int d) {
std::cout << "int: " << d << '\n';
}
int main() {
Weekday day = Sunday;
print(day);
print(0);
}
Or even something like the following where operator<< has many overloads.
Code:
#include <iostream>
enum Weekday { Sunday, Monday, Tuesday };
std::ostream& operator<<(std::ostream& os, Weekday d) {
switch (d) {
case Sunday: os << "Sunday"; break;
case Monday: os << "Monday"; break;
case Tuesday: os << "Tuesday"; break;
default: os.setstate(std::ios_base::failbit);
}
return os;
}
int main() {
Weekday day = Monday;
std::cout << day << '\n';
}