(I know what the scope resolution operator does, and how and when to use it.)
Why does C++ have the ::
operator, instead of using the .
operator for this purpose? Java doesn't have a separate operator, and works fine. Is there some difference between C++ and Java that means C++ requires a separate operator in order to be parsable?
My only guess is that ::
is needed for precedence reasons, but I can't think why it needs to have higher precedence than, say, .
. The only situation I can think it would is so that something like
a.b::c;
would be parsed as
a.(b::c);
, but I can't think of any situation in which syntax like this would be legal anyway.
Maybe it's just a case of "they do different things, so they might as well look different". But that doesn't explain why ::
has higher precedence than .
.
Because someone in the C++ standards committee thought that it was a good idea to allow this code to work:
Basically, it allows a member variable and a derived class type to have the same name. I have no idea what someone was smoking when they thought that this was important. But there it is.
When the compiler sees
.
, it knows that the thing to the left must be an object. When it sees::
, it must be a typename or namespace (or nothing, indicating the global namespace). That's how it resolves this ambiguity.The reason is given by Stroustrup himself:
(Bjarne Stroustrup A History of C++: 1979−1991 page 21 - § 3.3.1)
Moreover it's true that
indeed
(Bjarne Stroustrup's C++ Style and Technique FAQ)
Unlike Java, C++ has multiple inheritance. Here is one example where scope resolution of the kind you're talking about becomes important:
Just to answer the final bit of the question about operator precedence:
Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.
Why C++ doesn't use
.
where it uses::
, is because this is how the language is defined. One plausible reason could be, to refer to the global namespace using the syntax::a
as shown below:Online Demo
I don't know how Java solves this. I don't even know if in Java there is global namespace. In C#, you refer to global name using the syntax
global::a
, which means even C# has::
operator.Who said syntax like
a.b::c
is not legal?Consider these classes:
Now see this (ideone):
b.f()
cannot be called like that, as the function is hidden, and the GCC gives this error message:In order to call
b.f()
(or ratherA::f()
), you need scope resolution operator:Demo at ideone