4

In the function called ::foo() I don't understand what the syntax is for. If it was foo::count_all() then I know that count_all is a function of class or namespace foo.

In the case of ::foo() what is the :: referencing?

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • 2
    Possible duplicate of [why prepend namespace with ::, for example ::std::vector](https://stackoverflow.com/questions/4925394/why-prepend-namespace-with-for-example-stdvector) – Fantastic Mr Fox Dec 22 '17 at 04:20

4 Answers4

4

The :: operator is calling a namespace or class. In your case it is calling the global namespace which is everything not in a named namespace.

The example below illustrates why namespaces are important. If you just call foo() your call can't be resolved because there are 2 foos. You need to resolve the global one with ::foo().

namespace Hidden {
    int foo();
}

int foo();

using namespace Hidden; // This makes calls to just foo ambiguous.

int main() {
    ::foo(); // Call to the global foo
    hidden::foo(); // Call to the foo in namespace hidden 
}
Jake Freeman
  • 1,700
  • 1
  • 8
  • 15
2

:: with nothing before it indicates the global namespace. eg:

int foo(); // A global function declaration

int main() {
   ::foo(); // Calling foo from the global namespace.
   ...
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
1

It is a function call, not a declaration, to the function foo() in the global scope. The :: in front of the function name means you explicitly want to call the global function foo(), and not some other version of foo() from some narrower scope.

E.g.

void foo()
{
  printf("global foo\n");
}

namespace bar
{
  void foo()
  {
    printf("bar::foo\n");
  }

  void test()
  {
    foo();
    ::foo();
  }
}

A call to bar::test() will print out:

bar::foo
global foo
Andrew Medlin
  • 461
  • 3
  • 11
0

By specifying the :: you were telling the system to look at the global namespace. See also this article

https://stackoverflow.com/a/6790112/249492

Below is an example by @CharlesBailey, we're inside of the "nest" namespace. You access to "x" can change to the upper namespace depending if you specify to use the global namespace or not.

namespace layer {
    namespace module {
        int x;
    }
}

namespace nest {
    namespace layer {
        namespace module {
            int x;
        }
    }
    using namespace /*::*/layer::module;
}
Damian
  • 1,209
  • 14
  • 24