This question already has answers here:
What does the "::" mean in C++?
(4 answers)
Closed last year.
I found this line of code where I'm working, but I don't quite understand its meaning:
virtual method1::method2::method3 f() = 0;
In the main function, I have method1::method2::method3.g1().g2(). I really don't understand. I know method::A where A is a class.
:: is a scope operator.
You may need to append multiple of them either when using nested classes (a class defined within another class) or when you use namespaces. Resolution is done the same way.
:: is the scope resolution operator. It allows you to statically traverse scopes such as namespaces and classes in order to reference the identifier you want.
I think what you have is not methods but namespaces and classes.
I am very new to C++ and found the following Code example.
Can the "::" operator be used in this way and why or should it only be used for declared namespaces?
class Test {
void dosmthng();
};
void Test::dosmthng() {}
The :: operator is called the Scope Resolution Operator.
Names declared inside the class are related to the class scope.Searching for names for class scope is subject to some rules.
In what cases is a name searched in class scope ?
If the name is used within a global function, the name must be used in one of 3 cases for the name to be searched in class scope.
If the name is used to the right of the point operator. (.)
If the name is used to the right of the arrow operator. (->)
If the name is used as the right operand of the scope resolution operator. (::)
The 3 important processes and sequences related to name searching are as follows.
Name Lookup =>
name is searched first.
Context Control=> Other rules of the language . For example, mistakes like using Rvalue where Lvalue is needed.
Access Control => A separate category of controls in Object Oriented programming languages. It is done at compile time.
The left operand of the scope resolution operator must be a name in C++.This name can be a namespace name, it can be a class name.Right operand if class name
it will be searched in the scope of that class.
To summarize, it is one of the important operators of the language used for name lookup.
The operator :: is commonly used for both of mentioned cases
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 am learning C++, and want to confirm few thins. I have seen that std::cin has :: operator which means that iostream.h file must have cin related code inside namespace std. Whereas if you include myclass.h and have class NOT inside namespace like this
//myclass.h
class x { void func(){}};
Then you don't need to do this myclass:x.func(); Instead i can do just this x.func();. Correct Becuase it's not inside namespace.
Secondly, :: can be used to define class functions outside of the class like in their cpp file. Correct?
Now my additional question is that are these two functions separate or one? do they just look different to me?
:: (scope resolution operator) is used for multiple purposes in C++?
It's only really serving one purpose - to help find the namespace and/or class/struct/union scope that an identifier's in.
The compiler knows to look first in the tightest scope then work its way back to the global scope, but it also considers any namespaces and identifiers you're "using" (e.g. using namespace xxx; or using ns1::identifier;).
Then you don't need to do this myclass:x.func(); Instead i can do just this x.func();
It has nothing to do with files on disk.
Secondly, :: can be used to define class functions outside of the class like in their cpp file. Correct?
Yes. When you define a member function outside its class, you use the class name so it's not deemed a distinct non-member function in the current scope.
Now my additional question is that are these two functions separate or one? do they just look different to me?
Just the one in the defining-member-function scenario above.
I have seen that std::cin has :: operator which means that iostream.h file must have cin related code inside namespace std.
I realize this isn't a question, but you said iostream.h and I wanted to point out that you should not use iostream.h because it is deprecated, use iostream instead.
Then you don't need to do this myclass:x.func(); Instead i can do just this x.func();. Correct Becuase it's not inside namespace.
This is correct. You could do the same thing if all of your code was inside a namespace rather than a class.
Secondly, :: can be used to define class functions outside of the class like in their cpp file. Correct?
Correct, so long as they have been declared, but not defined, in the class scope this is allowed and usually considered preferable for readability.
Now my additional question is that are these two functions separate or one? do they just look different to me?
If both are in the class scope already, void x::func(){} and void func(){} result in the same thing (one would call both by using x a; a.func(), for example).
EDIT: In response to the comment, you can define a namespace basically the same way you define a class, as:
namespace funcs
{
void innerfunc(){}
void outerfunc();
void funcs::scopedfunc(){}
}
funcs::outerfunc();
As you can infer from std, these are called as free functions, rather than being called from an object like a non-static class function.
int main()
{
funcs::innerfunc();
using namespace funcs;
outerfunc();
}
Then you don't need to do this myclass:x.func(); Instead i can do just this x.func();.
Note that neither of these will compile. You cannot use the dot operator with a class; you can only use it with an object. Specifically, myObject.func(); serves an entirely different purpose than MyClass::func() { }. The first calls the member function func() on the object named myObject. The later is used to define the function func() which belongs to the scope of MyClass.
I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e.
class someScope::someClass;
Instead, the full declaration has to be used as follows:
namespace
{
class someClass;
}
Can someone explain why this is the case?
UPDATE: To clarify, I am asking why this is the case.
You can't declare a class outside its namespace, because the compiler could not be aware of the type of someScope.
namespace{ } is required to declare the existence of namespace, and then, declare class someClass into your scope.
Seems as though the answer lies in the C++ specification:
3.3.5 "Namespace scope" in the standard.
Entities declared in a namespace-body
are said to be members of the
namespace, and names introduced by
these declarations into the
declarative region of the namespace
are said to be member names of the
namespace.
A namespace member can also be
referred to after the :: scope
resolution operator (5.1) applied to
the name of its namespace or the name
of a namespace which nominates the
member’s namespace in a
using-directive;
I am not sure why. Maybe because, in your first code snippet, someScope is undeclared. It can be a namespace, or a class name. If someScope is a class name, you can't independently forward declare a class member of another class.