Observe the following:
#include <iostream>
#include <string>
#include <cstdlib>
int main(){
static std::string foo = "inside main";
struct Bar{
Bar(){
std::cout << "I can see " << foo << '\n';
}
};
Bar b;
return EXIT_SUCCESS;
}
The output of this program is: “I can see inside main”.
Why can the class constructor look outside the class definition and find foo?
It only works, if foo is static, inside the same function as the class definition, and comes before the class definition.
Help convince me that it’s not violating the rules of scope. Why is it possible? What are the advantages and pitfalls of such an implementation?
Because
struct Baris inside main()’s namespace andfooisstatic. The standard says:So your code doesn’t violate the standard.