Whovian
Whovian

Reputation: 375

C++ accessing global variables/objects in a namespace with a variable/object with the same name

#include <iostream>
#include <string>
using namespace std;

string a;

namespace myNamespace
{
    string a;
    void output()
    {
        cout << a << endl;
    }
}

int main()
{
    a = "Namespaces, meh.";
    myNamespace::a = "Namespaces are great!";
    myNamespace::output();
}

The result is "Namespaces are great!". So is there any way to access the global string a inside of the namespace myNamespace instead of just the local one?

Upvotes: 12

Views: 6631

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63190

Like this:

void output()
{
    cout << ::a << endl;  //using :: = the global namespace 
}

Upvotes: 17

Related Questions