Search code examples
c++scopeblock

Scope resolution operator with shadowing in blocks


Not that you'd write code like this, but trying to better understand the scope resolution operator ::. Is it possible to access the version of foo that stores the value 2 in the inner scope without having it be a named namespace?

#include <iostream>
using std::endl;
using std::cout;
 
// Some global.
int foo = 1;

int main() {
  cout << foo << endl; //<-- Prints 1.

  // Shadow it:
  int foo = 2;
  cout << foo << endl; //<-- Prints 2.

  // Access the global:
  cout << ::foo << endl; //<-- Prints 1.

  {
     // More shadows:
     int foo = 3;
     cout << foo << endl;     // The local. 3.
     cout << ::foo << endl;   // The global, 1
     //cout << ::main::foo << endl; //<-- Obviously invalid.
     // ::..::foo                   // Totally not it.

     // Is it possible go access 2 here?
  }
}

Thanks!


Solution

  • Is it possible go access 2 here?

    No, it is not possible to access the 2nd foo as it has been hidden from the inner foo.

    One thing that you can do if you must use the outer foo from #2 is that you can create an alias for it with some other name like ref and then use that alias as shown below:

    // Some global.
    int foo = 1;
    
    int main() {
      cout << foo << endl;
    
      // Shadow it:
      int foo = 2;
      cout << foo << endl; 
    
      
      cout << ::foo << endl; 
    
      {
    //------------v-------------->create alias lvalue reference
         int const& ref = foo;
    
         int foo = 3;
         cout << foo << endl;     
         cout << ::foo << endl;  
         
         // possible to access foo from #2 using alias ref but not using the name foo
         std::cout<<ref; //prints 2
      }
    }