Sorry for the not very descriptive question title. I’m not very sure how to describe this, hopefully I can make it better later if someone can explain this to me.
I was about to come on here and ask why the following example was working. It was exhibiting the behaviour I was hoping for but I wasn’t sure why or whether it was standard or whether I just got lucky with the compiler. Anyway, in sorting out a minimal working example to post here I found that it wasn’t doing what I thought at all. So here it is …
struct Foo {
enum BAR { A, B, C, D, E };
private: typedef BAR BAR;
};
int main(int argc, char* argv[]) {
int x = (Foo::BAR)42;
int y = Foo::D;
}
What seems to be happening, and what I was quite pleased about, is that, Foo takes on the enum constants after which BAR is made private. So I get no error on int y = but I get a Foo::BAR is private error at int x=. However this seems to only work with 5 or more constants in the enum, remove that E and it all compiles fine, i.e. BAR remains public.
What’s at work here? Thanks.
(PS. Compiler is GCC 4.4.3)
I can verify your results about four vs. five enum elements… this looks like an obscure GCC bug.
As for “what’s at work here”, it’s due to a technicality between different symbol namespaces in C++ (inherited from C). See this answer for more details.
If you don’t want a symbol named
BARto be exposed, simply omit the tag name:If you declare a named public enum, then no matter what you do, even if you hide the name using a typedef, outsiders can access the enum using an elaborated type specifier. Trying to hide a symbol name in this way is fruitless:
Is there any particular reason you want the constants to be public while the enum name remains private?