Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:: without a namespace

Tags:

c++

namespaces

Consider the following line of code:

::CGContextRef cgContext = cocoa::createCgBitmapContext( surface );

How come there's no namespace specified before :: ? Does that mean it's using the same namespace as the class you're in?

like image 747
pwang Avatar asked May 11 '11 15:05

pwang


People also ask

Is namespace necessary in C++?

All C++ standard library types and functions are declared in the std namespace or namespaces nested inside std thus it is widely used in most of the programs.

Can we create class without namespace in C#?

class can exists without namespace. class without namespace cannot be accessed in other namespace. Yes, namespace is used to just grouping and it is not mandatory.

What if namespace is not used?

Namespaces are basically just to organize your code. using namespace std; is used to inform the compiler to look for the io functions in this standard library. If it is not used, the compilation will flag an error that cin/cout is undefined. It is compiler dependent.

Should I use std :: or using namespace std?

To put it as an advice: Do not use "using namespace" (std or other) at file scope in header files. It is OK to use it in implementation files.


1 Answers

:: in ::CGContextRef means global namespace, which means CGContextRef is defined in the global namespace.

int x = 10; 
namespace test
{
    int x = 100;
    void f() 
    {
         std::cout << x << std::endl;  //prints 100
         std::cout << ::x << std::endl; //prints 10
    }     
}

See complete demo here : http://www.ideone.com/LM8uo

like image 178
Nawaz Avatar answered Sep 20 '22 17:09

Nawaz