Scope

A variable does not exist until it is declared.

 

When the area of code in which it was declared exits, the variable ceases to exist. Its contents are lost.

 

The scope of a variable is therefore the validity of that variable within the location in which it was declared.

 

Sometimes this is also referred to as the duration of which the variable is valid, since a variable can be thought of as having a lifetime in which it exists.

 

The duration of a variable definition, and the extent to which it is accessible from other places, is called the variable’s scope.

 

Global scope refers to the validity of variables that are declared in the main body of the program outside of all functions, including main(), and is valid throughout the entire program. It is generally considered not good practice to declare globally scoped variables.

 

Local scope refers to validity of variables that are declared within an enclosing code block’s curly braces { }.

 

Locally scoped variables can only be used within their declared block and do not exist outside of their block.

 

Scope is delineated by curly braces { }

 

 

In this example, count belongs to method1 and is only accessible by method1. It is inaccessible by method2, which has no idea that it even exists:

 

In this example, method1 and method2 have their own copies of count, independent and inaccessible to each other:

 

 

Object scope

Object scope is used when an attribute needs to be shared by more than one method within the same object.

 

In this example, count is declared outside the scope of method1 and method2, but within scope of the class and is therefore available to all methods within the class. All methods use the same (and only) copy of count for the object:

 

 

In this example, count is declared outside the scope of the methods, but then also within each method, which provides three separate memory locations all with the name count individual to their context:

*Note: the keyword this is a reference to the current object

 

 

Class scope

It is also possible to share an attribute, by making is static:

*Note: potential pitfall, when one object instantiated by the class changes the value of count, it would be changed for all other instances of the object using count

Leave a Reply