I have viewed some source that contained an identifier with a scope operator preceding it.
Ex:

::var

What does that mean/do?

Recommended Answers

All 2 Replies

This is C++'s scope resolution operator. This resets the scope of that variable in this case. You see this all the time when you declare a class and then implement its functions elsewhere.

For example, you have

class myClass {
int myFunction();
};

int myClass::myFunction()
{
 ...
}

The :: is giving access to the function in myClass outside of this scope.

Now for another example, using var

int var = 3;

int main()
{
    float var = 4.5;
    {
          double var = 6.5;
          int myVar = ::var;
    }
}

Here, using the scope resolution operator, myVar is going to be set to 3.

Hope this helps

::name is explicitly specifying that name is in global namespace

example 1:

int i = 3;
int main()
{
   int i = 4;
   if(true)
   {
       int i = 5;
       int j = ::i; //j is set to 3
   }  
}

example 2:

int main()
{
   int i = 4;
   if(true)
   {
       int i = 5;
       int j = ::i; //ERROR there is no i in the global namespace. If you wanna access the i just outside the block, that is, the one with value 4, well, you can't :)  
   }  
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.