0

A local class cannot access local variables of the function in which it is defined.

Why is this? What is the reason for this rule in C++?

Community
  • 1
  • 1

1 Answers1

2

It's a reasonable question to ask, especially since some common languages, e.g. Python, allow this.

However, think about this situation if references to locals were allowed and hypothetically this code could compile.

struct MyClass {
    virtual fetchValue() = 0;
};

MyClass* somefunction(){
    int localVariable = 123;
    struct HypotheticalClass : public MyClass {
        virtual int fetchValue(){ return localVariable; }
    };
    return new HypotheticalClass()
}

Now, upon returning this MyClass derivative at the end of somefunction(), it maintains reference to a now-invalid stack location. Boom.

Of course there is a multitude of other ways to inappropriately reference invalid stack locations, for example, passing a reference to that local variable to your class to get the access anyway. And the same issue exists for lambdas which can have access to the local reference or do a copy.

As for an authoritative answer as to why, I skimmed through 4th edition Stroustrup and see nothing useful to report.

Thanks for the interesting question.

John Griffin
  • 377
  • 2
  • 8