CPP Namespace

What is namespace?

  • Namespaces are used to reduce the chance of class name conflicts.
  • Namespaces notations are similar in some ways to classes.
  • Items declared within the namespace are owned by the namespace.
  • Namespaces can be nested within other namespaces.
  • There a several ways to denote whatever namespace:

    Giving namespace statement outside the main function, is a global notation that applies to all classes and functions.

    // my first program in C++
    #include <iostream>
    using namespace std; // Notation that applies to all classes and functions
    int main ()  {
      cout << "Hello World!";
      return 0;
    }

    Giving namespace statement inside {} braces, will cause that the namespace can only be used by statements inside those braces.

    #include <iostream>
    int main()  {
     using namespace std; // only for the code inside the braces
     cout << "Hello there.\n"; // \n results in a new line
     return 0;
    }

    Giving namespace statement inside {} braces that is selective on which function to use, will cause that the function(s) in the namespace can only be used inside those braces.

    #include <iostream>
    int main()  {
       using std::cout; // only for the code inside the braces
                        // and the selected function(s)
     cout << "Hello there.\n"; // \n results in a new line
     return 0;
    }

    Giving namespace given directly on the function(s) to use.

    #include <iostream>
    int main()  {
     // Directly on selected function(s)
     std::cout << "Hello there.\n"; // \n results in a new line
     std::cout << "Hello there.";
     std::cout <<  std::endl;  // std::endl results in a new line
     return 0;
    }

    Creating a Namespace:
    namespace Window
    {
        void move( int x, int y) ;
    
        class List
        {
            // ...
        }
    }
    

  • All the elements of the standard C++ library are declared within what is called a namespace, which has the name std.
  • You can create many occurrences of a named namespace.
  • These multiple occurrences can occur within a single file or across multiple translation units.
  • When this occurs, the separate instances are merged together by the compiler into a single namespace if they have the same name.
Prev. in menu cpp/intro/Namespace.php Next in menu
Prev. in menu cpp/intro/Namespace.php Next in menu
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.