Logo Questions Linux Laravel Mysql Ubuntu Git Menu

What does the syntax ::function_name mean in c++?




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?

like image 496
tokia burke Avatar asked Mar 07 '23 07:03

tokia burke

2 Answers

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 
like image 162
Jake Freeman Avatar answered Mar 09 '23 20:03

Jake Freeman

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

int foo(); // A global function declaration

int main() {
   ::foo(); // Calling foo from the global namespace.
like image 41
Fantastic Mr Fox Avatar answered Mar 09 '23 21:03

Fantastic Mr Fox