What is the scope of variables declared in a class

2020-02-06 03:41发布

问题:

I was curious, what is the scope of variables declared inside a class constructor which are not data members of that class?

For example, if a constructor needs an iterating int i, will this variable be destroyed after the constructor finishes, or is it then global for the program?

回答1:

In this sense a constructor is like any other function - any variable declared inside has usual scope limitations and they all surely go out of scope and get destroyed once constructor is finished.



回答2:

Like any other function, if it's a local variable it will be "destroyed" at the end of the function. Local scope.



回答3:

As it often happens, you could be mixing the notions of scope and lifetime, so I'll address both.

The scope of a name declared inside a constructor is the same as the scope of any local name (the fact that it is a constructor makes no difference whatsoever): the scope of the name extends to the end of the block in which the name is declared (and it can have "holes" when the name is hidden by a declaration of an even "more local" entify with the same name).

The lifetime of am object defined inside a constructor is governed by the same rules as the lifetime of any locally-defined object (the fact that it is a constructor makes no difference whatsoever): an object with automatic storage duration is destroyed at the end of its scope, while an object with static storage duration lives forever.



回答4:

Variables declared in the class constructor are available inside the scope of the class constructor and nowhere higher.

public MyClass() {
   int i = 0; // i is only available inside this constructor.
              // It can't be used in any other function of this class or any other.
}


回答5:

Local variables, regardless of the function, are destroyed when they go out of scope. They do not become 'global.'



回答6:

Scope can either be static (lexical) or dynamic. Most languages use lexical scope, which means scope is determined by the text of the program (e.g. "inside the set of braces where it's defined"), not by the meaning of what you wrote.

http://en.wikipedia.org/wiki/Scope_(programming)