What does :: do?

Often when viewing code online I see :: used. What does it do and how/when should I use it? Thanks!
Scope resolution operator. It tells compiler to look for this name in some namespace/class

For example std::cin tells that cin is in std namespace (all standard library belongs here)
std::crono::steady_clock::now() tells compiler to look for now function inside steady_clock class which is inside crono namespace, which is inside std namespace.
As MiiNiPaa said.

One of the only things I'd really feel worth adding is the situation with scoped enums. If you're using a newer VS compiler by default (which uses C++11) you can have something like

1
2
3
4
5
enum Color { red, green, blue};

Color myColor;

myColor = Color::red;


If you're using MinGW for example however, (which is the standard with Code::Blocks) you'll have to make sure you're using C++11 first.
Last edited on
so when I write using namespace std; I dont need to put std::cin ? when calling cin?
Last edited on
so when I write using namespace std; I dont need to put std::cin ? when calling cin?
You don't need to (however you still can), but I advise to minimise usage of using directive and abstain from its usage at global scope, as it can introduce hard to debug bugs and name collisions. And whatever you do, do not ever use it in headers.
There are plenty of cases where using is a bad idea, with a commonly used library like Boost, you'll probably see why.
:: can also be sued to access a global variable.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
// this is global
const int a = 5;

void f(int a) {
  // this is local
  std::cout << a << std::endl;    // whatever you give as input
  std::cout << ::a << std::endl; // 5
}

int main() {
  f(3);
}
Last edited on
^ Generally I'd tend to avoid having to use the global namespace in the first place though
In object oriented programming. It is use to link the function definition and declaration.
1
2
3
4
5
6
7
class SomeClass {
public:
void func (); // function declaration
};
void SomeClass::func() {  // notice the :: operator
//definition
}



it may also use for calling a global variable
example:
1
2
3
4
5
6
7
8

#include <iostream>
int global = 3; // global variable
int main() {
int global = 2; // local variable
std::cout << ::global << std::endl; /* it will output 3 instead of 2. because of the :: operator which will call the global variable. */

}
Last edited on
Topic archived. No new replies allowed.