Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 12: Namespaces

Namespaces

Namespaces (Section 9.2)

  • namespace – a collection of name definitions. A namespace is a group of classes, objects, datatypes, variables, and functions which are accessible only when referenced as part of that namespace. The
    1
    using

    statement is the most common way of referencing a namespace.

  • The using statement has scope just like a variable declaration. It applies only to code after it, inside the block of code within which it is executed. So different parts of your code may use different namespaces.
  • As an alternative to the
    1
    using

    statment, you can fully qualify all names you use from a namespace like this:

    1
    std::cout

  • You may define your own namespaces using this simple format:
        namespace persiko
        {
          class myClass
          {
            private:
              int w;
    
            public:
              myClass();
              int myFunction(int x);
          };
        }
        ...
        namespace persiko
        {
          myClass::myClass()
          {
            w = 0;
          }
    
          int myClass::myFunction(int x)
          {
            w += x;
            return w;
          }
        }
        ...
        {
          using namespace persiko;
          myClass z;
          cout << z.myFunction(5);
        }
  • Namespace example program