Coupon Accepted Successfully!


Local Versus Global Object

The object declared outside all function bodies is known as global object. All functions can access the global object. The object declared inside a function body is known as local object. The scope of local object is limited to its current block. We learnt the behavior of constructor and destructor with local and global object.

When global and local variables are declared with the same name, the scope access operator is used to access the global variable in the current scope of local variable. We know that the local variable gets first precedence than the global variable. The same is applicable for objects. When a program contains global and local objects with the same name, the local object gets first preference in its own block. In such a case, scope access operator is used with global object. The following program describes this.

9.28 Write a program to show difference between local and global object.

Explanation: In the above program, the object t is declared in local as well as global scope. In function main(), using scope access operator and t, the function show() is invoked. The first time function show() is invoked using global object. The second call to function show() is made by local object. The local object does not require scope access operator. The scope access operator is used only when the same name for object is used in global and local scopes. If scope access operator is not used before object, for both times function show() is invoked by local object.

Test Your Skills Now!
Take a Quiz now
Reviewer Name