1A namespace is a declarative region that provides a scope to the
2 identifiers (the names of types, functions, variables, etc) inside
3 it. Namespaces are used to organize code into logical groups and to
4 prevent name collisions that can occur especially when your code base
5 includes multiple libraries
1Namespaces avoids name collisions bacause of large libraray in c++.
2This feature was not supported in C
1//namespace is a declarative region to provide scope for identifiers
2#include <bits/stdc++.h>
3
4using namespace std; //including namespace std for cin and cout
5//my custom namespace for variables and functions
6namespace abc
7{
8 void fun()
9 {
10 cout<<"Hello world"<<endl;
11 }
12 int x=10;
13}
14using namespace abc;
15int main()
16{
17 cout<<10;
18 fun();
19 return 0;
20}
1namespace Parent
2{
3 inline namespace new_ns
4 {
5 template <typename T>
6 struct C
7 {
8 T member;
9 };
10 }
11 template<>
12 class C<int> {};
13}
14
1//Header.h
2#include <string>
3
4namespace Test
5{
6 namespace old_ns
7 {
8 std::string Func() { return std::string("Hello from old"); }
9 }
10
11 inline namespace new_ns
12 {
13 std::string Func() { return std::string("Hello from new"); }
14 }
15}
16
17#include "header.h"
18#include <string>
19#include <iostream>
20
21int main()
22{
23 using namespace Test;
24 using namespace std;
25
26 string s = Func();
27 std::cout << s << std::endl; // "Hello from new"
28 return 0;
29}
30