This question already has an answer here:
- Why can I use auto on a private type? 2 answers
I found something weird in C++ that I don't understand why it's happening.
I have an inner class with a private struct definition, it looks like this:
#include <string>
class A {
private:
class B {
private:
struct C {
int lol;
std::string ok;
};
public:
B() {}
C* makething();
};
public:
A() {}
void dostuff();
};
C* makething();
simply returns a new struct C, like this:
A::B::C* A::B::makething()
{
C* x = new C;
return x;
}
So now if the implementation for void dostuff();
is like this:
void A::dostuff()
{
B x = B();
B::C* thing = x.makething(); // compile error
thing->lol = 42;
thing->ok = "some words";
std::cout << thing->lol << " " << thing->ok;
}
It gives me the error: C2248 'A::B::C': cannot access private struct declared in class 'A::B'
This was expected, because struct C is declared as private within class B.
However, if I change the line B::C* thing = x.makething();
to auto thing = x.makething();
, it will compile and no longer gives me the error that struct C is private, and then I can modify the struct's values like I did in the makething()
function.
Why is this happening? Why does the auto
keyword allow me to create instances of privately declared structs or classes?
Edit: I am using Visual Studio Community 2015 as the compiler.
Aucun commentaire:
Enregistrer un commentaire