[C++] Namespace

binh12A3
2 min readDec 1, 2021

Why “using namespace std” is not recommended ? and When we should declare a namespace ? 😎😎

What is namespace ?

In brief, namespace is like a box, a group, a declarative region which contains objects/symbols like datatypes, functions, variables,… (namespace scope).

How to use namespace ?

Let’s make examples with the standard std namespace

  • We could preface the namespace before the API call i.e : “std::
  • We could use “using namespace std” to shorten the code (not recommended)
  • We could explicitly specify which objects we want to use by “using std::xxx” (recommended)

Why we should not do “using namespace std” ?

  • By using the entire std space, you’ll make your code is hard to determine
  • A common problem of “using namespace std” is if you try to create your own function and give it the same name that is already present in std namespace, that can lead to name collisions and ambiguity.
  • So it’s recommended to use only things we really need instead of using the entire std space.

Why we need to declare a namespace ?

  • It’s a very bad practice to name anything that overlaps with the standard lib. If you are going to do it, it’s best to explicitly declare your namespace. This way when the project grows larger, it will be very easy to determine.
  • To avoid naming conflict especially with common popular function’s name like init() by using the preface operator “::” to avoid naming conflict.

NOTE :

Because we include cpp files, not header files, so we need to use the static keyword to resolve the multiple definition error i.e “void __cdecl mobile::hello(void)” (?hello@mobile@@YAXXZ) already defined in main.obj”. Because the static variable is created only 1 time and will be reused next time. For more info about static keyword, you can find here.

Instead of using static keyword, we can include header files + Fileguards in header files.

  • Group common functionality or a particular company project.
  • Classifying/Categorizing then we could easily change which one we want to use depending on the namespace i.e : Dog, Cat
  • We could use namespace xxx{} as an OOP way to limit the access or as a container for common objects. Who want to use it, they should include “using namespace xxx;”

Additional points

  • We could use “using namespace std” in function scope.
  • We could have nested namespaces
  • We could make the alias for namespaces

--

--