Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean if a method call starts with two colons?

A coworker routinely writes something like this:

::someObject->someMethod(anAttribute, anotherAttribute);

someObject is a global variable.
Those two colons seem strange to me. The code compiles and runs just fine without them.

The coworker claims that those colons make someObject explicitly global and thus prevent confusion with a possible local someObject. I would think that you would not be able to define someObject locally if it was already defined globally?

Could you shed some light on what those colons mean and whether they are necessary?

like image 912
bastibe Avatar asked Sep 06 '10 09:09

bastibe


1 Answers

Your coworker is right. You can indeed define a local someObject which would hide the global someObject within that scope:

SomeClass* someObject = ...;

// here the global object is visible
someObject->someMethod(anAttribute, anotherAttribute); // calls the global object

void someMethod() {
  SomeClass* someObject = ...;
  // here the local object hides the global
  ::someObject->someMethod(anAttribute, anotherAttribute); // calls the global object
  someObject->someMethod(anAttribute, anotherAttribute);   // calls the local object
}

// here again only the global object is visible
someObject->someMethod(anAttribute, anotherAttribute); // calls the global object

Scopes can be embedded within other scopes recursively, thus you may have a namespace within global scope, a class within a namespace, an inner class within the class, a method within an inner class, a block within the method... etc. And you may have variables/classes/methods/... of identical names in any of these scopes. So identifying what entity a specific name is referring to is not a trivial task in C++. It is known as name lookup.

In brief, whenever the compiler finds a name, it looks up that name starting from the innermost scope. I.e. inside someMethod, the name someObject is matched by the object defined locally. ::someObject overrides this default behaviour and makes the compiler search only within the outermost (global) scope, thus it finds the global object instead ofthe local.

like image 174
Péter Török Avatar answered Oct 11 '22 18:10

Péter Török