Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Namespaces 

Introduction

Example Using the Scope Resolution Operator

Better Approach Than Using Global Variables

Introduction

 

Namespaces allow you to group entities like classes, objects and functions under a name. This way the global scope can be divided in "sub-scopes", each one with its own name.

The format of namespaces is:

namespace identifier

{

   code 

}
Where identifier is any valid identifier and code is the variables that are included within the namespace (can also be classes, etc).  

For example

namespace myNameSpace

{

    int a, b;

}

 

In this case, the variables a and b are normal variables declared within a namespace called myNamespace. In order to access these variables from outside the myNamespace namespace we have to use the scope operator ::. For example, to access the previous variables from outside myNamespace we can write:

 

myNameSpace::a          //:: is a scope resolution operator that will be covered in the course

myNameSpace::b

The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors.

 

Example using the Scope Resolution Operator

 

An Example

Note that var is used twice without difficulty because of the use of namespaces

 

#include "stdafx.h"

#include <iostream>

using namespace std;

 

namespace first

{

  int var = 5;

}

namespace second

{

  double var = 3.1416;

}

int main ()

{

  cout << first::var << endl;                                 //:: is the scope resolution operator - see below

  cout << second::var << endl;

  return 0;

}

 

Note the following use of the scope resolution operation and the omission of using namespace std;

#include <iostream>
 
int main()
{
    std::cout << "Hello, world!\n";
    return 0;
}

 

 

 

Better Approach than Using Global Variables

 

#include "stdafx.h"

#include <iostream>

using namespace std;

namespace prices

{

  double costCokes = 1.05;

  double costFries = 2.05;

  double costBurgers = 3.05;

}

void testCase();

void announcePrices();

int main ()

{

    testCase();

    announcePrices();

    return 0;

}

void testCase()

{

   //cout<<costBurgers;                                                          this will give "undeclared variable" error

}

void announcePrices()

{

   using namespace prices;                                                  //allows access to prices namespace

   cout<<"Cost of cokes: "<<costCokes<<endl;

   cout<<"Cost of burgers: "<<costBurgers<<endl;

   cout<<"Cost of fries: "<<costFries<<endl;

}