Why does C++ need the scope resolution operator?

Karu picture Karu · Feb 18, 2012 · Viewed 43.7k times · Source

(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 ..

Answer

Nicol Bolas picture Nicol Bolas · Feb 18, 2012

Because someone in the C++ standards committee thought that it was a good idea to allow this code to work:

struct foo
{
  int blah;
};

struct thingy
{
  int data;
};

struct bar : public foo
{
  thingy foo;
};

int main()
{
  bar test;
  test.foo.data = 5;
  test.foo::blah = 10;
  return 0;
}

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.