CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: namespace

  1. #1
    Join Date
    Apr 2002
    Posts
    60

    namespace

    What is empty namespace for?

    namespace
    {
    class A
    {
    .......
    ......
    };

    class B
    {
    ......
    .....
    }
    };

  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Namespaces allow you to group a set of global classes, objects and/or functions under one name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.

    Sometimes you just want to group something within a namespace which should not known outside the local context. In these cases it would be useless to come up with a unique name, which might collide with another one. In this case you can use unnamed namespaces.
    Code:
    namespace
    {
      class A
      {
      };
    }
    To be able to use the grouped members of an unnamed namespace there exists an implicit 'using' directive. The former example is equivalent to
    Code:
    namespace $$$
    {
      class A
      {
      };
    }
    
    using namespace $$$;
    '$$$' is a different name in every scope an unnamed namespace is declared. In addition unnamed namespaces are different for each translation unit. Therefore there is no possibility to access members from an unnamed namespaces from different translation units.

  3. #3
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    Basically, and unnamed namespace serves the same purpose as declaring static objects at file scope: it keeps them local to the file and unusable outside it.
    Code:
    /* oldstyle.c */
    
    static int local_global;
    
    static void local_function();
    
    /*------------- */
    
    // newstyle.cpp
    
    namespace
    {
        int local_global;
        void local_function();
    }
    
    // -----------------
    In both cases, "local_global" and "local_function" are available for use within the file (technically, "translation unit") that they are declared in, but not outside of it.
    When using C++, prefer unnamed namespace to static declaration.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured