20.4.  Namespaces

[ fromfile: namespaces.xml id: namespaces ]

Example 20.11. src/namespace/a.h

#include <iostream>
namespace A {
    using namespace std;
    void f() {
        cout << "f from A\n";
    }

    void g() {
        cout << "g from A\n";
    }
}

Example 20.12. src/namespace/b.h

#include <iostream>

namespace B {
    using namespace std;
    void f() {
        cout << "f from B\n";
    }

    void g() {
        cout << "g from B\n";
    }
}


Example 20.13. src/namespace/namespace1.cc

#include "a.h"
#include "b.h"

int main() {
    A::f();
    B::g();
}
Output:

f from A
g from B



  1. The using directive:

    using namespace namespaceName

    imports the entire namespace into the current scope.

  2. The using declaration:

    using namespaceName::identifier

    imports a particular identifier from that namespace into the current scope.

Example 20.14. src/namespace/namespace2.cc

#include "a.h"
#include "b.h"

int main() {
    using A::f;         1
    f();
    using namespace B;  2
    g();                3
    f();                4
}
Output:

f from A
g from B
f from A



1

Declaration - brings A::f() into scope.

2

Brings all of B into scope.

3

Okay.

4

Ambiguous!


Example 20.15. src/namespace/namespace3.cc

#include "a.h"
#include "b.h"

int main() {
    using namespace A; 1
    f();
    using namespace B; 2
    g();
    f();              
}
Output:

OOP> gpp namespace3.cc
namespace3.cc: In function `int main()':
namespace3.cc:10: call of overloaded `g ()' is
ambiguous
b.h:6: candidates are: void B::g()
a.h:6:                 void A::g()
namespace3.cc:11: call of overloaded `f ()' is
ambiguous
b.h:4: candidates are: void B::f()
a.h:4:                 void A::f()
OOP>


1

brings all of A into scope

2

brings all of B into scope