What exactly is the purpose of the scope resolution operator? I can't seem to find anything in my book telling exactly what it does. It just seems to dance around the subject somewhat.

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();

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

}

operator :: known as scope resolution operator has been introduced to access an item that is outside the current scope. This operator is also used in distiguishing class members and defining class methods.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.