Monday, August 22, 2011

using namespace in C++ Sample code

Here I am going to present a short example of using namespaces in C++.
There are three files named

  1. a.h
  2. b.h
  3. namespace.cpp

copy all the three files using your editor and compile the code as shown in example below.
--------------

/*
 * a.h
 */
 #include <iostream>
 namespace A {
    using namespace std;
    void f() {
       cout << "f from A\n";
    }
    void g() {
       cout << "g from A\n";
    }
 }
--------------
/*
 * b.h
 */
 #include <iostream>
 namespace B {
    using namespace std;
    void f() {
       cout << "f from B\n";
    }
    void g() {
       cout << "g from B\n";
    }
 }
--------------
/*
 * namespace.cpp
 */
 #include "a.h"
 #include "b.h"

 #include <iostream>

 int main() {
    A::f();
    B::g();
    return 0;
 }
/*
 [sgupta@rhel55x86 namespaces]$ c++ -o namespace namespace.cpp
 [sgupta@rhel55x86 namespaces]$ ./namespace
 f from A
 g from B
 [sgupta@rhel55x86 namespaces]$
*/

No comments:

Post a Comment