• Home
  • 3.22 Scope Resolution Operator (::)

3.22 Scope Resolution Operator (::)

View Categories

3.22 Scope Resolution Operator (::)

1 min read

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.
  • ::number accesses the global variable number.
  • The variable number declared inside main() hides the global variable within the local scope.
  • Using ::number bypasses 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::cout and std::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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *