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?
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?
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 foo
s. 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
}
::
with nothing before it indicates the global namespace. eg:
int foo(); // A global function declaration
int main() {
::foo(); // Calling foo from the global namespace.
...
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
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;
}