Cpp - class Namespaces

Introduction

C++ uses namespaces to avoid naming conflicts with global identifiers.

Within a namespace, the global scope is subdivided into isolated parts.

A normal namespace is identified by a name preceded by the namespace keyword.

The elements that belong to the namespace are then declared within braces.

namespace myLib 
{ 
   int count; 
   double calculate(double, int); 
   // . . . 
} 

This example defines the namespace myLib that contains the variable count and the function calculate().

Elements belonging to a namespace can be referenced directly by name within the namespace.

To reference an element from outside of the namespace, supply the namespace by adding the scope resolution operator :: before the element name.

myLib::count = 7;     // Outside of myLib 

This allows you to distinguish between identical names in different namespaces.

You can use the scope resolution operator :: to reference global names declared outside of any namespaces.

To do so, simply omit the name of the namespace.

You can access a global name hidden by an identical name defined in the current namespace using the following.

::demo();  // Not belonging to any namespace 

namespaces do not need to be defined contiguously.

You can reopen and expand a namespace you defined previously at any point in the program

namespaces can be nested, and you can define a namespace within another namespace.

Demo

#include <string>       // Class string defined within 
                        // namespace std 
namespace MySpace 
{ 
    std::string mess = "Within namespace MySpace"; 
    int count = 0;         // Definition: MySpace::count 
    double f( double);     // Prototype:   MySpace::f() 
} 
namespace YourSpace 
{ 
   std::string mess = "Within namespace YourSpace"; 
   void f( )                     // Definition of 
    {                             // YourSpace::f() 
       mess += '!'; 
    } /*from ww  w .  j  av a  2  s  .com*/
} 
namespace MySpace                      // Back in MySpace. 
{ 
    int g(void);            // Prototype of MySpace::g() 
    double f( double y)           // Definition of 
    {                             // MySpace::f() 
      return y / 10.0; 
    } 
} 
int MySpace::g( )              // Separate definition 
{                              // of MySpace::g() 
    return ++count; 
} 

#include <iostream>   // cout, ... within namespace std 
int main() 
{ 
  std::cout << "Testing namespaces!\n\n" 
              << MySpace::mess << std::endl; 
  MySpace::g(); 
  std::cout << "\nReturn value g(): " << MySpace::g() 
              << "\nReturn value f(): " << MySpace::f(1.2) 
              << "\n---------------------" << std::endl; 
  YourSpace::f(); 
  std::cout << YourSpace::mess << std::endl; 
  return 0; 
}

Result

Related Topics