Visibility or availability of a variable in a program is called as scope. There are two types of scope in c++ programs.
- Local scope
- 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.
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.
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.