Table of Contents
The scope resolution operator (::) is used to access names that belong to a particular scope. It allows a program to distinguish between identifiers with the same name that exist in different scopes, such as namespaces, classes, and the global scope.
One of its most common uses is qualifying Standard Library objects with the std namespace, such as std::cout and std::cin. It is also used to access global variables that are hidden by local variables.
Source Code #
#include <iostream>
int number = 100;
int main()
{
int number = 50;
std::cout << "Local Number : " << number << '\n';
std::cout << "Global Number: " << ::number << '\n';
return 0;
}
Output #
Local Number : 50
Global Number: 100
Explanation #
- The scope resolution operator (
::) specifies the scope to which an identifier belongs. ::numberaccesses the global variablenumber.- The variable
numberdeclared insidemain()hides the global variable within the local scope. - Using
::numberbypasses the local variable and refers directly to the global variable. - The scope resolution operator is also commonly used to access members of namespaces, such as
std::coutandstd::cin. - It is frequently used with classes to define member functions outside the class definition.
- The operator helps eliminate ambiguity when identical names exist in different scopes.
return 0;terminates the program successfully.