What is the scope of variables declared in a class constructor?
Solution 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.
Solution 2
Like any other function, if it's a local variable it will be "destroyed" at the end of the function. Local scope.
Solution 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.
Solution 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.
}
Solution 5
Local variables, regardless of the function, are destroyed when they go out of scope. They do not become 'global.'
Tony R
Updated on June 04, 2022Comments
-
Tony R almost 2 years
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? -
Tony R about 15 yearsThanks! I just wasn't sure if the constructor was considered as a normal function.
-
AnT stands with Russia over 14 yearsNo entirely accurate. Objects defined with static storage duration go out of scope, but don't get destroyed once the constructor is finished.
-
Caleth about 7 years@AnT how does that differ from statics in any other function?