Namespaces in C++

Namespaces in C++

Namespaces decide the problem of naming conflicts between different fragments of code. For example, you might be writing some code that has a function called calculate(). One day, you decide to start using a third-party library, which also has a calculate() function. The compiler has no way of knowing which version of calculate() you are referring to within your code. So namespaces come to the resolve such issues, when code names overlap To specify code in a custom namespace, simply put it within a namespace block. The C++ language provides a single global namespace called std.

The std namespace

std namespace contains entire C++ standard library
Old-style headers (vector.h, string.h, etc) still put everything in the global namespace
Better to use new-style headers (vector, string, etc)
For C library, new-style headers start with ”c” (cstdio, cstdlib, etc)

A namespace definition begins with the keyword namespace followed by the namespace.

// namespaces
namespace namespace_name {
//...some code

To call the namespace-enabled version of either function or variable.

// namespaces
 name::some code; // code could be variable or function.

How to declare namespace? To place code in a namespace, simply enclose it within a namespace block

// namespaces.h
 namespace mySpace {
 void calculate();

How to implement method or function in a namespace?

// namespaces.cpp
#include “namespaces.h”

namespace mySpace {
void calculate() {
//called from namespace mySpace
std::cout << calculate();

By putting your version of calculate() in the namespace “mySpace” it is isolated from the calculate() function provided by the third-party library. To call the namespace-enabled version of calculate():

Calls the calculate() function in the “mySpace” namespace.

 Example using different namespace
 // example namespaces
 #include <iostream>
 //c++ startard namespace
 using namespace std;

// our own namespace
 namespace mycodinglab
 int myVar = 16;
 int calc(int p){return p*2;};

//globar space
 int myVar = 32;
 int calc(int p){return p*2;};

int main () {

//print our namepace
 cout << mycodinglab::myVar << endl;
 cout << mycodinglab::calc(5) << endl;

//print from global
 cout << myVar << endl;
 cout << calc(10) << endl;

return 0;
 }//end of main

You must be logged in to post a comment.

Proudly powered by WordPress   Premium Style Theme by
%d bloggers like this: