#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?
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.
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.
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.
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.
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.
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 .
Like this:
void output()
{
cout << ::a << endl; //using :: = the global namespace
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With