Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does prepending "::" to a function call do in C++? [duplicate]

Possible Duplicate:
What is the meaning of prepended double colon “::” to class name?

I have been looking at a legacy C++ code and it had something like this:

::putenv(local_tz_char);
::tzset();

What does this syntax of prepending "::" to the function calls mean? Google-fu is failing me.

like image 777
DVK Avatar asked Nov 25 '11 21:11

DVK


2 Answers

It means that the functions putenv() and tzset() will be looked up by the compiler in the global namespace.

Example

#include <iostream>

using namespace std;

//global function
void foo()
{
    cout << "This function will be called by bar()";
}

namespace lorem
{
    void foo()
    {
        cout << "This function will not be called by bar()";
    }

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

int main()
{
    lorem::bar(); //will print "This function will be called by bar()"
    return 0;
}
like image 70
Nasreddine Avatar answered Sep 20 '22 08:09

Nasreddine


Also known as Scope resolution operator

In C++ is used to define the already declared member functions (in the header file with the .hpp or the .h extension) of a particular class. In the .cpp file one can define the usual global functions or the member functions of the class. To differentiate between the normal functions and the member functions of the class, one needs to use the scope resolution operator (::) in between the class name and the member function name i.e. ship::foo() where ship is a class and foo() is a member function of the class ship.

Example from Wikipedia:

#include <iostream>

// Without this using statement cout below would need to be std::cout
using namespace std; 

int n = 12; // A global variable

int main() {
  int n = 13; // A local variable
  cout << ::n << endl; // Print the global variable: 12
  cout << n   << endl; // Print the local variable: 13
}
like image 21
sll Avatar answered Sep 22 '22 08:09

sll