C++ enum of type char, ignored by the compiler or unexpected behaviour?
c++, enums
Solution
Without the cast, the compiler first searches for an appropriate member function of `std::ostream`, and it finds one -- the one for an `int`. So it implicitly converts your 1-byte number of type `anyoldname` to an `int` and calls the member function.
Compiling your program with g++ 4.8.1, two definitions for `ostream::operator<<` are seen:
U std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@GLIBCXX_3.4
U std::ostream::operator<<(int)@@GLIBCXX_3.4
The first one is for `endl` and the second one is for your enum.
With the explicit cast to char, the compiler is able to find a perfect match in the global `std::operator<<` function that takes an `ostream` and a `char` as an input. It then uses this function rather than doing an implicit cast (to an `int` again) in order to call an `ostream` member function.
The two symbols become:
U std::ostream::operator<<(std::ostream& (*)(std::ostream&))@@GLIBCXX_3.4
U std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char)
and your values are printed as characters rather than their decimal values.
Problem
I did a little test with an enum, here is what I have: ``` enum anyoldname : char { aa = 'a', ab = 'b', ac = 'c', ad = 'd' }; int main() { anyoldname i_have_an_enum_here = aa; // Would expect i_have_an_enum_here to be of type char? std::cout << i_have_an_enum_here << std::endl; return 0; } ``` Output is: `98`, unless I cast explicitly to char like so: ``` std::cout << (char)i_have_an_enum_here; ``` Or change `anyoldname` to `char`. Why is the value `98` printed instead of `b` ? By the way `sizeof()` returns `1`, ie; 1 byte, a `char`.