Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"auto" type deduction compiles while explicit type gives error [duplicate]

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.

like image 803
Creris Avatar asked Jul 06 '14 18:07

Creris


Video Answer


2 Answers

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.

like image 165
Alan Stokes Avatar answered Sep 21 '22 15:09

Alan Stokes


auto is supposed to work like that, yes, and yes that means that it can expose private types.

like image 33
Cheers and hth. - Alf Avatar answered Sep 21 '22 15:09

Cheers and hth. - Alf