Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we use "::" operator on global functions / objects?

Tags:

c++

syntax

I have seen this used in various places. C++ programmers will often use the :: operator right before a global function call.

e.g

::glGenBuffers( 1, &id );

Why is this? Why not just use:

glGenBuffers( 1, &id );
like image 983
Ben Avatar asked Jan 10 '23 22:01

Ben


2 Answers

To avoid accidental namespace clashing. For example if you current namespace would have glGenBuffers which does something different from the "good" glGenBuffers with :: you can specify to call the glGenBuffers which is in the global namespace.

like image 175
Ferenc Deak Avatar answered Jan 13 '23 13:01

Ferenc Deak


The problem is 1) names in inner scopes hide names in outer scopes and 2) there can be ambiguous of function calls when using directive is used.

For example (ambiguity)

#include <algorithm>

using namespace std;

void swap( int &x, int &y )
{
   int tmp = x;
   x = y;
   y = tmp;
}

int main()
{
   int x = 5, y = 10;

   //swap( x, y ); compiler error: what function to call?

   ::swap( x, y ); // the user defined function is called

   std::swap( x, y ); // the standard function is called.
}

Another example of hidding names

#include <iostream>

void f() { std::cout << "::f()\n"; }

namespace MyNamespace
{
   void f() { std::cout << "MyNamespace::f()\n"; }

   void g() { f(); } // calls MyNamespace::f()

   void h() { ::f(); } // calls ::f()
}


int main()
{
   MyNamespace::g();
   MyNamespace::h();
}
like image 29
Vlad from Moscow Avatar answered Jan 13 '23 12:01

Vlad from Moscow