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++?

9
  • 2
    I know scope of a variabe,this is a restriction that is put on local class by the author of C++,so get your facts straight first. Commented Oct 1, 2016 at 13:52
  • 1
    In C++, classes don't inherit scope like Java classes do. Commented Oct 1, 2016 at 14:03
  • 1
    May be it can be an exception made by the author of C++ but the question is why he made this exception ? Commented Oct 1, 2016 at 14:11
  • 3
    I'm not sure why this is getting so many down-votes. Sure, it may be difficult to find an authoritative answer here, but it doesn't make this a bad question. And it doesn't mean an authoritative, non-speculative answer doesn't exist. Commented Oct 1, 2016 at 14:14
  • 1
    @juanchopanza: There's not much meat to it, but I don't really know what more meat there could be. Anyway, I've edited out the equivocation and tidied it up a bit; perhaps that'll help. Commented Oct 1, 2016 at 14:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.