I am using Visual Studio 2012, and I've found something that is kind of weird. I'm not writing something that I necessarily require to be compatible across multiple compilers, but it may become later(when the code is put on web, users don't want to get compiler errors), but I don't want to write something that is wrong, or just not native.
So this is test code:
class A{
class B{
public:
int i;
};
B myB;
public:
B& getB() { return myB; }
};
int main()
{
A a;
A::B& b = a.getB();
auto& b2 = a.getB();
}
The first line inside main pops error C2248: 'A::B' : cannot access private class declared in class 'A'
whereas the second line compiles normally. I wonder, is auto supposed to work like this or is this another bug in Visual Studio?
I don't have any other compiler I can test it on with
You can even write stuff like std::cout << b2.i << "\n";
and it compiles perfectly fine
As per πάντα ῥεῖ's comment, I tried ideone with gcc 4.8.1 and it compiles in the same way, first line is error, second line is perfectly fine.
I believe it's supposed to work like that. Access applies to names, not the entities they refer to.
Even without auto
it has always been legal to e.g. pass the result of getB
to a function expecting a B
.
auto
is supposed to work like that, yes, and yes that means that it can expose private types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With