Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Whovian Avatar asked May 06 '12 23:05

Whovian


People also ask

Can we access a global variable if there is a local variable with the same name in C?

Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.

How do you access global variable if there is a local variable with same name in Python?

It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals() returns a dictionary object of all global variables and their respective values. Using the name of the variable as a key, its value can be accessed and modified.

How do you access global variable if there is a local variable with same name in Java?

Using Scope resolution operator (::): In C++, we can use the scope resolution operator (::) to access a global variable if we have a local variable with the same name.

Can have one global variable and one local variable of same name and can we access each of them in same function?

It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.

Can 2 global variable have same name?

In other words, all global variables with the same name will be converted to be one variable - so your int a; and int a = 25; will be referring to the same int -sized piece of memory. Formally called tentative definition in C.

How do I access variables from namespace?

The namespaces in some namespaces may also be nested. To access them we are required to use the scope resolution operator :: operator the number of times that are there to access them. When we want to access the variable sample , we need to use example1::example2::example3::sample .


1 Answers

Like this:

void output()
{
    cout << ::a << endl;  //using :: = the global namespace 
}
like image 64
Tony The Lion Avatar answered Sep 29 '22 13:09

Tony The Lion