years ago before anyone heard about namespaces programmers had a terrible time avoiding name conflicts in their own code and the libraries they used. That was the main reason (I think) for the introduction of namespaces -- you can have as many objects with the same name as you wish as long as each object is contained in a different namespace. you will commonly see code such as
std::cout << "Hello Worod" << std::endl;
This is identifying the namespace (std) of cout and endl. For objects in global namespace, such as all the win32 api functions just preceed the object with two colons as in the following code. This is really more useful when there is another function called MessageBox() in another namespace that your program also might use. Its just telling the compiler which function to call.
::MessageBox(0,"Hello World","Message",MB_OK);
c++ classes have the same affect as formal namespace
class MyClass
{
MyClass();
static void SayHello() {std::cout << "Hello World" << std::endl;}
};
// call the SayHello method
MyClass::SayHello();
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Lets say you have a global variable and a local variable with the same name. When you compile it, the compiler will use the local variable, and not the global variable. If you prefix the variable name with ::[variablename], then the compile uses the global variable.
#include <iostream>
using namespace std;
int amount = 123; // A global variable
int main()
{
int amount = 456; // A local variable
cout << ::amount << endl // Print the global variable
<< amount << endl; // Print the local variable
}
You can do this even for function names.
Note that you can use this to specify only global variables. Not the variables in the next outermost scope.
#include <iostream>
using namespace std;
int amount = 123; // A global variable
int main()
{
int amount = 1234 ; // the local variable in the outermost scope
{
int amount = 456; // A local variable
cout << "Innermost Scope" << endl ;
cout << ::amount << endl // Print the global variable not the value with 1234
<< amount << endl; // Print the local variable in current scope
}
cout << "Outermost Scope" << endl ;
cout << ::amount << endl // Print the global variable
<< amount << endl; // Print the local variable in current scope
}
WolfPack
Postaholic
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115