...

View Full Version : The use of :: and what does it mean.



GameCodingNinja
05-26-2009, 03:46 PM
I've seen calls that just begin with :: for example...

::MessageBox(NULL, "Error!", "Error", MB_OK | MB_ICONWARNING);

but it works fine like this too.

MessageBox(NULL, "Error!", "Error", MB_OK | MB_ICONWARNING);


What is the reason for :: ?

satchel
05-26-2009, 04:23 PM
I assume you mean c++, it's a way of defining the namespace you want to use:


#include <iostream>
using namespace std;
int main () {
cout<<"Test";
return 0;
}

OR


#include <iostream>
int main () {
std::cout<<"Test";
return 0;
}

Both of these are valid, and the second is useful if you want to use a specific namespace for a specific piece of code. It's actually the bit before and after the "::" that's important.

oracleguy
05-26-2009, 04:55 PM
More precisely it is the scope operator. You use it to reference items in a different scope. Like if you had a class called 'A' that had a public class inside of it called 'B' and you wanted to instantiate B from outside of A, you would have to do:


A::B myClass;

GameCodingNinja
05-26-2009, 05:16 PM
Thanks guys. That helps me understand a bit of what's going on.

I understand scope and namespaces. So when :: is used in the correct way, it makes sense like...

std::string myStr;

Windows API calls are not encapsulated in a class, struct or namespace. So why someone would write...

::MessageBox(NULL, "Error!", "Error", MB_OK | MB_ICONWARNING);

... is beyond me. I can call any function with :: in front of it and the compiler doesn't seem to care.

In this code I'm looking at, the windows API calls begin with :: but doesn't seem necessary.

oracleguy
05-26-2009, 05:21 PM
Thanks guys. That helps me understand a bit of what's going on.

I understand scope and namespaces. So when :: is used in the correct way, it makes sense like...

std::string myStr;

Windows API calls are not encapsulated in a class, struct or namespace. So why someone would write...

::MessageBox(NULL, "Error!", "Error", MB_OK | MB_ICONWARNING);

... is beyond me. I can call any function with :: in front of it and the compiler doesn't seem to care.

In this code I'm looking at, the windows API calls begin with :: but doesn't seem necessary.

It is probably just someone's coding style.

There can be reasons do to something like that, like if you were in a class that had a member method called MessageBox and you wanted to call the one at the root scope.

satchel
05-26-2009, 05:22 PM
I can't see any reason why they would use that, it could be a short hand for std I suppose, written into the compiler?

oracleguy
05-26-2009, 05:24 PM
I can't see any reason why they would, it could be a short hand for std I suppose, written into the compiler?

No it isn't, like the OP said, the API functions are in the global scope.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum