Two kinds of scope are global scope and local scope. An object with global scope is declared as a global variable. Objects with global scope can be accessed from anywhere n the program. Global objects are constructed immediately before the program begins execution. Global objects are destructed after the program has terminated normally. Objects with local scope are constructed at the site of their declaration and are destructed when control reaches the end of the program unit (function, method, block) that contains the declaration.
Global and local scopes are illustrated in the following example. In this example, the globalWindow object has global scope; it can be accessed from within the function, from within the for loop and from within the then clause. The functionWindow object has a local scope that is the body of function. Similarly the loopWindow object has a scope limited to the for loop and the ifWindow object has a local scope limited to the then clause of the if construct.
Frame globalWindow; // global scope void function() { Frame functionWindow; // start of functionWindow scope ... for( int i=0; i<10; i++) { Frame loopWindow; // start of loopWindow scope ... if (i < 5) { Frame ifWindow; // start of ifWindow scope ... } // end of ifWindow scope } // end of loopWindow scope } // end of functionWindow scopeWhile object with a global scope exist throughout the execution of the entire program, objects with local scope do not. For example, the functionWindow object above is constructed when control enters the function and is destructed when control leaves the function via a return or by encountering the end of the function. Similarly, the loopWindow object is constructed and destructed on each iteration of the loop and the ifWindow is constructed when the then clause is entered and destructed when the end of the then clause is reached.
|
Exercises |