[C++] Namespace

What is namespace ?

How to use 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.
  • 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




“Developer never die” 😎🇻🇳

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium


7 reasons why you should opt for ONLYOFFICE Workspace for your business

Known vs Unknown Framework

Configuring Hadoop Cluster using Ansible Playbook | Task-11.1 | ARTH

Max Points on a Line — Google Coding Interview Question

Zap Protocol Beta 2.0 Development Update

How to find a software developer Internship

The Road Ahead For Sensu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


“Developer never die” 😎🇻🇳

More from Medium

Overriding I/O Streams in C++

Basics on C++ Pointers

C++ Templates: What is std::enable_if and how to use it?

Friendly Introduction Pointers in C++