So I was looking through a few old C++ Test Books and I found the solution to one of the questions very cool! I have never seen this "syntax" before and wanted to ask if anyone knows how it actually works and why it isnt taught widely!
Question: Give the output to the following code ->
int g =10; //TAKE NOTE OF THIS VARIABLE
void func(int &x, int y){
x = x-y;
y = x*10;
cout << x << ',' << y << "\n";
}
void main(int argc, char** argv){
int g = 7; //Another NOTE
func(::g,g); // <----- "::g" is different from "g"
cout << g << ',' << ::g << "\n";
func(g,::g);
cout << g << ',' << ::g << "\n";
}
The Output:
3,30
7,3
4,30
4,3
My question was how does the "::(variable)" syntax work exactly? It gets the variable stored outside of the main but where is that memory stored(Stack/Heap)? Can we change the value of that "Global" variable through pointers?
I thought this might allow for some really cool implementations, and wanted to share this knowledge with those like me did not know of this :)
My question was how does the "::(variable)" syntax work exactly?
:: is the scope resolution operator. With the name of a class or namespace before it, it means that the name after it is scoped inside that class or namespace. With, as here, nothing before it, it means that the name after it is scoped in the global namespace; that is, it's declared outside any classes, functions, or namespaces.
Often, you can refer to a global variable by name without ::. It's needed here since the global is hidden by a local variable with the same name. This is one reason to avoid global variables: the meaning of code can change if you add a declaration that hides it.
where is that memory stored(Stack/Heap)?
It's in static storage, neither on a stack nor the heap. The storage is allocated when the program begins, and lasts until it ends.
If the variable has a complicated type, it might not be initialised until some time after the program starts; and you might get obscure and painful bugs when your code uses it before initialisation. This is another reason to avoid global variables.
Can we change the value of that "Global" variable through pointers?
Yes. Your example does that, albeit with a reference rather than a pointer. It can also be changed directly, e.g. ::g = 42;, by any code at any time, so it's hard to reason about the state of a program that contains them. This is yet another reason to avoid global variables.
I thought this might allow for some really cool implementations
Global variables are nearly always more trouble than they're worth, for the reasons I've mentioned here and others. I'd avoid them if I were you.
Plain g means "use the most local g", ::g means use the global g.
More general, example::g means "use the g from namespace example".
Also, if you can somehow avoid it (and you usually can), do not use global variables and do not use trickery like this, it is very error-prone.
Static variables are in a category of their own: they're not really on "the stack" or "the heap." There is a specific section of your process' memory space set aside to hold static variables which is distinct from the stack or the heap. See the link given for a full discussion.
You can still use this variable as you would any other, and you can indeed take a pointer to it and change its value via the pointer.
As others have suggested, don't get too excited about this: global variables are frowned upon. They are often a sign of poor design, and there are many real-world disadvantages and pitfalls.
By prepending :: to a variable or function, you tell the compiler that it should look for this variable/function in the global namespace, i.e. outside the function's scope.
:: is the scope resolution operator. If you have some bar identifier declared within the foo namespace, you can use foo::bar to denote it. If you have the scope resolution operator with nothing preceding it, then it denotes the global namespace. That's why ::g refers to the g in the global namespace.
It gets the variable stored outside of the main but where is that memory stored(Stack/Heap)? Can we change the value of that "Global" variable through pointers?
I'm not sure why these questions arose. They are using the global variable g just as you would be able to if the local g wasn't declared. The only reason the :: is required is because there are two g identifiers. You can do pretty much anything with it that you would be able to do with any other object with the same type.
The :: in C++ is called the scope resolution operator. It's documented in many places (here for example). It provides a way to name variables that may be in a different scope than the current code. There is an optional scope specification in front of the :: (A::g, for instance, for a namespace A); no scope specification indicates the "global" scope. Anything you can do with variables (including modifying through pointers) can be done with variables that have a scope resolution operator. Where the variable lives is defined by what scope it was defined in.
Static variables (global or not) are in one of a couple of places, depending on the compiler and possibly on how they are initialized. See, for example, this thread.
Related
I found this line of a code in a class which I have to modify:
::Configuration * tmpCo = m_configurationDB;//pointer to current db
and I don't know what exactly means the double colon prepended to the class name. Without that I would read: declaration of tmpCo as a pointer to an object of the class Configuration... but the prepended double colon confuses me.
I also found:
typedef ::config::set ConfigSet;
This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:
class Configuration; // class 1, in global namespace
namespace MyApp
{
class Configuration; // class 2, different from class 1
function blah()
{
// resolves to MyApp::Configuration, class 2
Configuration::doStuff(...)
// resolves to top-level Configuration, class 1
::Configuration::doStuff(...)
}
}
Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.
The :: operator is called the scope-resolution operator and does just that, it resolves scope. So, by prefixing a type-name with this, it tells your compiler to look in the global namespace for the type.
Example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...
X11/xterm
...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...
std::cout
...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.
3) C++ always searches the global namespace (like having / implicitly your PATH).
General discussion on namespaces and explicitness of symbols
Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
:: is the scope resolution operator. It's used to specify the scope of something.
For example, :: alone is the global scope, outside all other namespaces.
some::thing can be interpreted in any of the following ways:
some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
some is a class available in the current scope and thing is a member object, function or type of the some class;
in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.
You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.
So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.
The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.
I hope this answer is complete and correct enough to help you understand scope resolution.
:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;
int x;
void f2()
{
int x = 1; // hide global x
::x = 2; // assign to global x
x = 2; // assign to local x
// ...
}
(This answer is mostly for googlers, because OP has solved his problem already.)
The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.
The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?
Use case - namespace clash
When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in #Wyatt Anderson's answer, plese see his example.
Use case - emphasise non-member function
When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:
class A {
void DoSomething() {
m_counter=0;
...
Twist(data);
...
Bend(data);
...
if(m_counter>0) exit(0);
}
int m_couner;
...
}
But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.
So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.
:: is a operator of defining the namespace.
For example, if you want to use cout without mentioning using namespace std; in your code you write this:
std::cout << "test";
When no namespace is mentioned, that it is said that class belongs to global namespace.
"::" represents scope resolution operator.
Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.
I found this line of a code in a class which I have to modify:
::Configuration * tmpCo = m_configurationDB;//pointer to current db
and I don't know what exactly means the double colon prepended to the class name. Without that I would read: declaration of tmpCo as a pointer to an object of the class Configuration... but the prepended double colon confuses me.
I also found:
typedef ::config::set ConfigSet;
This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:
class Configuration; // class 1, in global namespace
namespace MyApp
{
class Configuration; // class 2, different from class 1
function blah()
{
// resolves to MyApp::Configuration, class 2
Configuration::doStuff(...)
// resolves to top-level Configuration, class 1
::Configuration::doStuff(...)
}
}
Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.
The :: operator is called the scope-resolution operator and does just that, it resolves scope. So, by prefixing a type-name with this, it tells your compiler to look in the global namespace for the type.
Example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...
X11/xterm
...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...
std::cout
...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.
3) C++ always searches the global namespace (like having / implicitly your PATH).
General discussion on namespaces and explicitness of symbols
Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
:: is the scope resolution operator. It's used to specify the scope of something.
For example, :: alone is the global scope, outside all other namespaces.
some::thing can be interpreted in any of the following ways:
some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
some is a class available in the current scope and thing is a member object, function or type of the some class;
in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.
You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.
So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.
The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.
I hope this answer is complete and correct enough to help you understand scope resolution.
:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;
int x;
void f2()
{
int x = 1; // hide global x
::x = 2; // assign to global x
x = 2; // assign to local x
// ...
}
(This answer is mostly for googlers, because OP has solved his problem already.)
The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.
The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?
Use case - namespace clash
When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in #Wyatt Anderson's answer, plese see his example.
Use case - emphasise non-member function
When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:
class A {
void DoSomething() {
m_counter=0;
...
Twist(data);
...
Bend(data);
...
if(m_counter>0) exit(0);
}
int m_couner;
...
}
But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.
So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.
:: is a operator of defining the namespace.
For example, if you want to use cout without mentioning using namespace std; in your code you write this:
std::cout << "test";
When no namespace is mentioned, that it is said that class belongs to global namespace.
"::" represents scope resolution operator.
Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.
I know that you can reuse variable names in C++, but I'm wondering whether I should. I'm not talking about reusing the variable itself, like with global variables. I'm talking about declaring and using a variable with a certain name in one scope, and then declaring and using another variable with the same name in a different scope. For example:
void Func1(int b) { /* Code here. */ };
void Func2(int b) { /* Different code here. */ };
void main()
{
{
int a=1;
// Do stuff with this variable.
}
{
int a=5;
// Do different stuff with this variable.
}
int b=10:
Func1(b);
Func2(b);
}
It seems like doing this would allow for shorter variable names and allow copy and pasting of code without having to change the variable names, but it might cause confusion. Is there a style guide or generally accepted practice about when to do this?
I searched for a similar question to this and I couldn't find anything. I found some stuff about global variables, but that's not what I'm looking for.
The alleged benefit of shorter variable names may be of interest, but what is of greater interest is shorter variable scopes. Generally, the smaller the scope of the variable is, the better. Therefore, declaring variables within small scopes is a good practice, and introducing naked scopes purely for that purpose is good practice too.
Once we have gotten that out of the way, then we go to the question of whether it should be okay to reuse a variable name in different scopes.
I would say that the most important thing about choosing a variable name is:
The name of a variable should be chosen in such a way as to best describe what the value of the variable stands for.
Any other concern is secondary. This means that the best name for a variable within a scope cannot in any way depend on what variables exist in other scopes.
This in turn means: reuse variable names across scopes, it is perfectly fine.
You certainly can do that, as they are in different scopes.
If you want your variables to help explaining the semantics of the surrounding code, you should use appropriately named variables.
If the given variable is just used for counting or similar, then using a general name like 'i' or 'j' in all cases it's an accepted practice.
You should read more about Variable Scope in C++.
You can reuse the variables out of the scope.
There are some naming conventions in programming, google yourself. This is a hit I got from it. Naming conventions are different from language to language, company to company, etc. But most of them have common features such as naming variables to have a meaning.
Remember these naming conventions are there to make our life easier. Using the naming conventions will help to understand your code for another person (or your futureself, someday).
It's always the option you choose, easy way or the (relatively) correct way .
I found this line of a code in a class which I have to modify:
::Configuration * tmpCo = m_configurationDB;//pointer to current db
and I don't know what exactly means the double colon prepended to the class name. Without that I would read: declaration of tmpCo as a pointer to an object of the class Configuration... but the prepended double colon confuses me.
I also found:
typedef ::config::set ConfigSet;
This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:
class Configuration; // class 1, in global namespace
namespace MyApp
{
class Configuration; // class 2, different from class 1
function blah()
{
// resolves to MyApp::Configuration, class 2
Configuration::doStuff(...)
// resolves to top-level Configuration, class 1
::Configuration::doStuff(...)
}
}
Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.
The :: operator is called the scope-resolution operator and does just that, it resolves scope. So, by prefixing a type-name with this, it tells your compiler to look in the global namespace for the type.
Example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...
X11/xterm
...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...
std::cout
...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.
3) C++ always searches the global namespace (like having / implicitly your PATH).
General discussion on namespaces and explicitness of symbols
Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
:: is the scope resolution operator. It's used to specify the scope of something.
For example, :: alone is the global scope, outside all other namespaces.
some::thing can be interpreted in any of the following ways:
some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
some is a class available in the current scope and thing is a member object, function or type of the some class;
in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.
You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.
So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.
The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.
I hope this answer is complete and correct enough to help you understand scope resolution.
:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;
int x;
void f2()
{
int x = 1; // hide global x
::x = 2; // assign to global x
x = 2; // assign to local x
// ...
}
(This answer is mostly for googlers, because OP has solved his problem already.)
The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.
The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?
Use case - namespace clash
When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in #Wyatt Anderson's answer, plese see his example.
Use case - emphasise non-member function
When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:
class A {
void DoSomething() {
m_counter=0;
...
Twist(data);
...
Bend(data);
...
if(m_counter>0) exit(0);
}
int m_couner;
...
}
But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.
So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.
:: is a operator of defining the namespace.
For example, if you want to use cout without mentioning using namespace std; in your code you write this:
std::cout << "test";
When no namespace is mentioned, that it is said that class belongs to global namespace.
"::" represents scope resolution operator.
Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.
I found this line of a code in a class which I have to modify:
::Configuration * tmpCo = m_configurationDB;//pointer to current db
and I don't know what exactly means the double colon prepended to the class name. Without that I would read: declaration of tmpCo as a pointer to an object of the class Configuration... but the prepended double colon confuses me.
I also found:
typedef ::config::set ConfigSet;
This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such:
class Configuration; // class 1, in global namespace
namespace MyApp
{
class Configuration; // class 2, different from class 1
function blah()
{
// resolves to MyApp::Configuration, class 2
Configuration::doStuff(...)
// resolves to top-level Configuration, class 1
::Configuration::doStuff(...)
}
}
Basically, it allows you to traverse up to the global namespace since your name might get clobbered by a new definition inside another namespace, in this case MyApp.
The :: operator is called the scope-resolution operator and does just that, it resolves scope. So, by prefixing a type-name with this, it tells your compiler to look in the global namespace for the type.
Example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...
X11/xterm
...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...
std::cout
...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.
3) C++ always searches the global namespace (like having / implicitly your PATH).
General discussion on namespaces and explicitness of symbols
Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
:: is the scope resolution operator. It's used to specify the scope of something.
For example, :: alone is the global scope, outside all other namespaces.
some::thing can be interpreted in any of the following ways:
some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
some is a class available in the current scope and thing is a member object, function or type of the some class;
in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.
You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.
So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.
The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.
I hope this answer is complete and correct enough to help you understand scope resolution.
:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;
int x;
void f2()
{
int x = 1; // hide global x
::x = 2; // assign to global x
x = 2; // assign to local x
// ...
}
(This answer is mostly for googlers, because OP has solved his problem already.)
The meaning of prepended :: - scope resulution operator - has been described in other answers, but I'd like to add why people are using it.
The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?
Use case - namespace clash
When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::. This case was described in #Wyatt Anderson's answer, plese see his example.
Use case - emphasise non-member function
When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:
class A {
void DoSomething() {
m_counter=0;
...
Twist(data);
...
Bend(data);
...
if(m_counter>0) exit(0);
}
int m_couner;
...
}
But it might happen that Twist is a sister member function of class A, and Bend is a free function. That is, Twist can use and modify m_couner and Bend cannot. So if you want to ensure that m_counter remains 0, you have to check Twist, but you don't need to check Bend.
So to make this stand out more clearly, one can either write this->Twist to show the reader that Twist is a member function or write ::Bend to show that Bend is free. Or both. This is very useful when you are doing or planning a refactoring.
:: is a operator of defining the namespace.
For example, if you want to use cout without mentioning using namespace std; in your code you write this:
std::cout << "test";
When no namespace is mentioned, that it is said that class belongs to global namespace.
"::" represents scope resolution operator.
Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.