(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 ..
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::aas 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::cis 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