Why is `::` called the 'scope resolution operator' when it doesn't act like an operator?

180 Views Asked by At

I can't think of a case when using :: to specify a scope would result in any code being generated. Every other operator I can think of actually (at least conceptually) generates code, it 'does something'.

So why is :: called the 'scope resolution operator' when it in no way behaves like an operator. It seems more to me like part of a name, a bit of lexical fluff like ... or the < and > surrounding a template parameter list, or even ;. Nobody calls ; the 'expression termination operator'.

Is there a specific reason it's called that (a quote from the standard on how it somehow behaves like an operator would be in order here)? Or is the name just historical baggage?

3

There are 3 best solutions below

5
Bathsheba On BEST ANSWER

But it is an operator, as much as say the member selection operator .:

#include <iostream>
int n;
int main()
{
    int n = 1;
    std::cout << ::n << " " << n;
}

and

#include <iostream>
struct N {
    int n = 1;
    operator int() const {return 0;}
};
int main()
{
    N n;
    std::cout << n << " " << n.n;
}

The output is the same in both cases.

5
Nicol Bolas On

Operators in C or C++ are not required to generate code. Operators which do not include, but are not limited to, sizeof, alignof, and even some uses of & (such as for types which decay to pointers).

4
Red.Wave On

In case you are specfically concerned about the term 'scope', it referes to a declaration(definition scope). A statement block - enclosed in curly braces - defines a declaration scope too. No identifier can be accessed outside its declaration scope unless the actual scope is properly resolved. Identifiers nested in unnamed scopes (eg. statement blocks) are buried in their definition scope forever. But identifiers in name scopes can be reference from outside via chaining of nesting scopes respectively, by means the 'scope resolution operator'. It is called an operator because it operates on 2(or 1) identifiers in order to result in a compile-time referential binding. Compare it to the member-access (the dot) operator that creates a callable binding. And please do not open the door towards hermeneutics, we are not practising philosophy in this forum.