Tutorial :What is the scope of variables declared in a class constructor?


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?



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.


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


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.


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.  }  


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


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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »