The following program gives segmentation fault.
#include <iostream>
using namespace std;
class A {
public:
static int& a;
};
int a = 42;
int& A::a = a;
int main() {
a = 100;
cout << A::a << endl;
return 0;
}
While the following program doesn't (where the name of the global variable has been changed from a to b, with associated changes in the definition of the static data member and in the main function):
#include <iostream>
using namespace std;
class A {
public:
static int& a;
};
int b = 42;
int& A::a = b;
int main() {
b = 100;
cout << A::a << endl;
return 0;
}
Can anyone explain this behavior? I mean, there shouldn't be any issues because of name and even if there were, the compiler should have thrown an error.
= ato= b, the intent is that the initializer is that global, not the same thing that is being initialized. This question is more about name lookup.