What are Namespaces

beginner c++11

In C++ namespaces help avoid naming conflicts between symbols (variables, functions, and classes). The most commonly used namespace is the C++ Standard Library’s namespace “std. Two colons (::) are always used to specify you are using a function or class from a given namespace.

#include <iostream>

// Declare our own namespace
namespace math {
  int add(int a, int b) {
    return a + b;
  }
}

int main() {
  std::cout << math::add(40, 2) << "\n";
}
42

In the above example main calls add from the math namespace and then prints the resulting value with the cout function from the std namespace.

Using Namespaces

You can use the using keyword in any scope to allow the using of specific symbols in the current scope.

#include <iostream>

// Declare our own namespace
namespace math {
  int add(int a, int b) {
    return a + b;
  }
}

int main() {
  // Use "add" from the "math" namespace
  using math::add;

  std::cout << add(40, 2) << "\n";
  std::cout << add(984, 737) << "\n";
}
42
1721

You can use the using namespace keyword in any scope to declare you are using all types declared in that namespace in the current scope. Be careful though as ambiguous name conflicts can occur when you do this as certain C++ namespaces, such as std, contain many names that will likely conflict with your own (or with the C standard library which does not have namespaces). It is therefore considered bad practice to write using namespace std; in your program.

#include <iostream>

// Declare our own namespace
namespace math {
  int add(int a, int b) {
    return a + b;
  }
}

int main() {
  // Use all symbols from the "math" namespace
  using namespace math;

  std::cout << add(40, 2) << "\n";
  std::cout << add(984, 737) << "\n";
}
42
1721

Namespace Aliases

Sometimes you may want to use a library from a third party but their namespace is bothersome to type or conflicts with one of your own. For this you can create a namespace alias. Here’s an example:

#include <iostream>

// Declare our own namespace
namespace robs_great_math_library {
  int add(int a, int b) {
    return a + b;
  }
}

// Create a namespace alias
namespace m = robs_great_math_library;

int main() {
  // Use the namespace alias we created
  std::cout << m::add(40, 2) << "\n";
  // We can still use the original name as well
  std::cout << robs_great_math_library::add(984, 737) << "\n";
}
42
1721

For more C++ By Example, click here.