Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) namespace

 

Keyword to make groups of functions and classes.

 

To call something from a certain namespace, write the namespace's name in front, followed by the scope operator, ::.

 

Functions and classes that are not put into a namespace reside in the global namespace.

 

The default namespace used is the global namespace. You can change this by using the keyword using.

 

All STL functions and classes are in the namespace std.

 

Example

 

In the example, three versions of the function SayHello reside in different namespaces: loud, soft and the global namespace.

 

 

 

#include <iostream>

 

namespace loud

{

  void SayHello() { std::cout << "HELLO WORLD!\n"; }

}

 

//SayHello in the global namespace, ::SayHello()

void SayHello() { std::cout << "Hello world\n"; }

 

namespace soft

{

  void SayHello() { std::cout << "H.e.l.l.o w.o.r.l.d...\n"; }

}

 

int main()

{

  loud::SayHello();     //Call loud::SayHello

  ::SayHello();         //Explicity call SayHello from global namespace

  SayHello();           //Call the SayHello used, which is ::SayHello by default

  using soft::SayHello; //Start using soft::SayHello

  SayHello();           //Call the SayHello used, which is soft::SayHello now

  soft::SayHello();     //Call soft::SayHello

}

 

 

This results in the following screen output:

 

HELLO WORLD!

Hello world

Hello world

H.e.l.l.o w.o.r.l.d...

H.e.l.l.o w.o.r.l.d...

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.