[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppNamespace

(C++) Namespace

Keyword that enables you to give functions different namespaces. This enables that multiple functions can have the same name, but different namespaces, without unexpected behaviour.

The most common namespace to be in, in namespace std. You can set the namespace using 'using namespace' or call the namespace and use the scope operator ('::').

Avoid using namespace std, as this will pollute the global namespace [5,6]. Use namespaces to express logical structure [1]. Place every non-local name, except main(), in some namespace [2]. Design a namespace so that you can conveniently use it without accidentally gaining access to unrelated namespaces [3]. Avoid very short names for namespaces [4].

Example of namespace

In this example, the function sayHello in defined in two different namespace and individually called.

  1. include <iostream>
namespace myNamespaceA { void sayHello() { std::cout << "Hello from myNamespaceA !" << std::endl; } } namespace myNamespaceB { void sayHello() { std::cout << "Hello from myNamespaceB !" << std::endl; } } int main() { myNamespaceA::sayHello(); myNamespaceB::sayHello(); }


Hello world program using 'using namespace'

  1. include <iostream>
using namespace std; int main(int argc, char* argv[]) { cout <<"Hello World" << endl; return 0; }


Hello world program using scope operator

  1. include <iostream>
int main() { std::cout <<"Hello World" << std::endl; }


namespace is not supported in C.

'namespace' links

Code links

Reference

27.5: Should I use using namespace std in my code? Probably not.

last edited (December 3, 2006) by bilderbikkel, Number of views: 9139, Current Rev: 16 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.