Reputation: 4320
This has been discussed here in case of lambda function. However, I came across this even for normal member function.
This simple code demonstrates:
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
struct A
{
A()
{
int y=x; // error C2326: 'wmain::A::wmain::A(void)' : function cannot access 'x'
}
};
return 0;
}
Microsoft says
The code tries to modify a member variable, which is not possible.
But here I am only trying to access the variable and not modifying, still I am getting error.
As a workaround given here we can pass variable by reference or can make it static. But I wonder is it really bug in compiler and if not why it has to be like this?
Upvotes: 0
Views: 549
Reputation: 206627
The compiler is right. From the C++ Draft Standard N3337:
9.8 Local class declarations
1 A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class shall not odr-use (3.2) a variable with automatic storage duration from an enclosing scope. [ Example:
int x;
void f() {
static int s ;
int x;
const int N = 5;
extern int q();
struct local {
int g() { return x; } // error: odr-use of automatic variable x
int h() { return s; } // OK
int k() { return ::x; } // OK
int l() { return q(); } // OK
int m() { return N; } // OK: not an odr-use
int *n() { return &N; } // error: odr-use of automatic variable N
};
}
local* p = 0; // error: local not in scope
— end example ]
Upvotes: 4