What are namespaces

suggest change

A C++ namespace is a collection of C++ entities (functions, classes, variables). When writing code within a namespace, named entities belonging to that namespace need not be prefixed with the namespace name. From outside, the name is found by qualification (namespace::entity) or by a using-declaration or using-directive. Example:

namespace Example
{
  const int test = 5;

  const int test2 = test + 12; //Works within `Example` namespace
}

const int test3 = test + 3; //Fails; `test` not found outside of namespace.

const int test3 = Example::test + 3; //Works; fully qualified name used.

Namespaces are useful for grouping related definitions together. Take the analogy of a shopping mall. Generally a shopping mall is split up into several stores, each store selling items from a specific category. One store might sell electronics, while another store might sell shoes. These logical separations in store types help the shoppers find the items they’re looking for. Namespaces help C++ programmers, like shoppers, find the functions, classes, and variables they’re looking for by organizing them in a logical manner. Example:

namespace Electronics
{
    int TotalStock;
    class Headphones
    {
        // Description of a Headphone (color, brand, model number, etc.)
    };
    class Television
    {
        // Description of a Television (color, brand, model number, etc.)
    };
}

namespace Shoes
{
    int TotalStock;
    class Sandal
    {
        // Description of a Sandal (color, brand, model number, etc.)
    };
    class Slipper
    {
        // Description of a Slipper (color, brand, model number, etc.)
    };
}

The global namespace has no name, but it can be denoted by ::. Example:

void bar() {
    // defined in global namespace
}
namespace foo {
    void bar() {
        // defined in namespace foo
    }
    void barbar() {
        bar();   // calls foo::bar()
        ::bar(); // calls bar() defined in global namespace
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents