Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can local class definitions access outside static variables from the same function?

Tags:

c++

static

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?

like image 864
Trevor Hickey Avatar asked Mar 05 '26 21:03

Trevor Hickey


1 Answers

Because struct Bar is inside main()'s namespace and foo is static. The standard says:

A class can be defined 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 can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.

So your code doesn't violate the standard.

like image 154
Nikos C. Avatar answered Mar 08 '26 14:03

Nikos C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!