Scope Resolution Operator ( :: )

Visibility or availability of a variable in a program is called as scope. There are two types of scope in c++ programs.

  1. Local scope
  2. Global scope

Local scope: visibility of a variable is local to the function in which it is declared.

Global scope: visibility of a variable to all functions of a program. Scope resolution operator in “::” is used to access global variables if same variables are declared as local and global.

Variable Scope and visibility using scope resolution operator
Variable Scope and visibility using scope resolution operator

Block2 contained in block l .Note that declaration in an inner block hides a declaration of the same variable in an outer block and therefore each declaration of x causes it to refer to a different data object. With in the inner block the variable x will refer to the data object declared there in.

In C, the global version of a variable can’t be accessed from with in the inner block. C++ resolves this problem by introducing a scope resolution operator ( :: ). This can be used to uncover a hidden variable.


:: variable–name;


int a=5;
void main()
int a=10;
cout<<”Local a=”<<a<<endl;
cout<<”Global a=”<<::a<<endl;
Expected output:
Local a=10
Global a=5

This scope resolution operator allows a programmer to define the functions somewhere else. This can allow the programmer to provide a header file .h defining the class and a .obj file built from the compiled .cpp file which contains the function definitions.

This can hide the implementation and prevent tampering. The user would have to define every function again to change the implementation.

Functions within classes can access and modify (unless the function is constant) data members without declaring them, because the data members are already declared in the class.

Related posts