Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Scope resolution operator (::)

The :: operator qualifies a name by specifying the namespace, class, or enumeration in which it is looked up. A leading :: denotes the global namespace. It helps distinguish hidden names and define member functions outside the class definition.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

::name
namespace_name::name
ClassName::member
EnumName::enumerator
outer::inner::name

:: is the scope resolution operator. It forms qualified names: demo::value names something in namespace demo, while demo::Counter::step proceeds through the namespace to a class and its member. Multiple qualifiers can be chained. An enumerator name can also be qualified, for example Color::red.

A leading :: denotes the global namespace: ::value refers to a global variable even when a local variable named value hides it. Without a leading ::, the first qualifier is resolved in the context of its use; demo::value therefore does not necessarily start lookup in the global namespace.

Class qualification does not mean that every member can be accessed without an object. A public static member can be referenced as Counter::step where the name Counter is visible. Calling an ordinary non-static member function requires an object, as in counter.next(5). The spelling int demo::Counter::next(int n) const defines a previously declared function outside the class. :: does not bypass access control and cannot be overloaded.

In the example, local value gives 30, ::value gives 10, demo::value gives 20, and demo::Counter::step gives 2. The call counter.next(5) returns 7. The example fits C++23; the supplied source is an evolving working draft, not a frozen C++23 text.

Examples

#include <iostream>

int value = 10;

namespace demo {
    int value = 20;

    struct Counter {
        static constexpr int step = 2;
        int next(int n) const;
    };
}

int demo::Counter::next(int n) const {
    return n + step;
}

int main() {
    int value = 30;
    demo::Counter counter;
    std::cout << value << ' ' << ::value << ' '
              << demo::value << ' ' << demo::Counter::step << ' '
              << counter.next(5) << '\n';
}

Result

30 10 20 2 7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources