Why does C++ need the scope resolution operator?

C++Server Side ProgrammingProgramming

The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary.

You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. For example,

Example

#include <iostream>  
using namespace std;  
int my_var = 0;
int main(void) {
   int my_var = 0;
   ::my_var = 1;  // set global my_var to 1
   my_var = 2;    // set local my_var to 2
   cout << ::my_var << ", " << my_var;
   return 0;
}

Output

This will give the output −

1, 2

The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope.

You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example,

Example

#include <iostream>
using namespace std;
class X {
   public:
   static int count;
};
int X::count = 10;    // define static data member
int main () {
   int X = 0;       // hides class type X
   cout << X::count << endl;     // use static member of class X
}

Output

This will give the output −

10
raja
Published on 15-Feb-2018 14:23:34
Advertisements