C++ namespace

 
######################## 
####   namespace    #### 
######################## 
 
namespace is a way to define a scope within code. it lets you group things. 
 
syntax is as below 
 
--------------------- 
namespace foo_bar 

int var; 
char* name; 
CParent cp; 
double calc(int x); 

 
foo_bar::var = 1234; 
--------------------- 
 
::  is called scope resolver/operator.   like CParent::getdata(),  std::cout,  etc 
 
you cannot define macro within a namespace as namespace is not related to pre-processor. 
 
 
###################### 
###  example code  ### 
###################### 
 
----------------------------------- 
namespace foo_bar 

int var;               // foo_bar namespace variable 

int var;                   // global variable 
 
int main() 

int var;               // local variable 
 
var = 678;             //  local variable. if no local var, then this will refer to the global var. 
foo_bar::var = 123;    //  foo_bar variable. obviously. 
::var = 999;           //  global var. 
 
return 0; 

------------------------------------ 
 
 
######################### 
###  using directive  ###   (to be distinguished from using declaration) 
######################### 
 
lets you omit the explicit call to the namespace. 
 
---------------------------------------- 
namespace foo_bar 

    int var; 

 
int main() 

using namespace foo_bar;  // this will let you infer foo_bar namespace within the immediate scope. 
var = 1234;  
 
return 0; 

---------------------------------------- 
 
alternatively, you can define the namespace more globally as below. 
 
---------------------------------------- 
namespace foo_bar 

    int var; 

 
using namespace foo_bar;    // this will work, but now you pretty much made this tantamount to simply declaring int var globally. 
 
int main() 

    var = 1234; 
 
    return 0; 

---------------------------------------- 
 
---------------------------------------- 
namespace foo_bar 

    int var; 
int num; 

 
namespace foo_bar2 

int var; 
int ber; 

 
 
int main() 

using namespace foo_bar; 
using namespace foo_bar2; 
 
    var = 1234;                // error, cannot resolve  between foo_bar::var  and foo_bar2::var 
    // so you should specify explicitly in this case. 
 
num = 567;                 // these two will work 
ber = 890; 
 
    return 0; 

---------------------------------------- 
 
 
############################# 
###    using declaration  ### 
############################# 
 
just like using directive, but this is more specific var/func level declaration of using a namespace. 
 
e.g. 
--------------------------------------- 
namespace foo_bar 

    int var; 
    int num; 

 
int main() 

using namespace foo_bar::var;   // only var, not num 
 
var = 1234;            // ok 
num = 9865;            // error 
 
return 0; 

--------------------------------------- 
 

  1. 2014-05-08 01:46:49 |
  2. Category : cpp
  3. Page View:

Google Ads