Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++
Prev Contents / Index Next

Creating a namespace

The creation of a namespace is notably similar to the creation of a class:

//: C10:MyLib.cpp
namespace MyLib {
  // Declarations
}
int main() {} ///:~

This produces a new namespace containing the enclosed declarations. There are significant differences from class, struct, union and enum, however:

  • A namespace definition can appear only at global scope, or nested within another namespace.
  • No terminating semicolon is necessary after the closing brace of a namespace definition.
  • A namespace definition can be “continued” over multiple header files using a syntax that, for a class, would appear to be a redefinition:
//: C10:Header1.h
#ifndef HEADER1_H
#define HEADER1_H
namespace MyLib {
  extern int x;
  void f();
  // ...
} 
#endif // HEADER1_H ///:~
//: C10:Header2.h
#ifndef HEADER2_H
#define HEADER2_H
#include "Header1.h"
// Add more names to MyLib
namespace MyLib { // NOT a redefinition!
  extern int y;
  void g();
  // ...
} 
#endif // HEADER2_H ///:~
//: C10:Continuation.cpp
#include "Header2.h"
int main() {} ///:~
  • A namespace name can be aliased to another name, so you don’t have to type an unwieldy name created by a library vendor:
//: C10:BobsSuperDuperLibrary.cpp
namespace BobsSuperDuperLibrary {
  class Widget { /* ... */ };
  class Poppit { /* ... */ };
  // ...
}
// Too much to type! I’ll alias it:
namespace Bob = BobsSuperDuperLibrary;
int main() {} ///:~
  • You cannot create an instance of a namespace as you can with a
    Thinking in C++
    Prev Contents / Index Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire