C++ Namespaces

πŸ“¦ C++ Namespaces

A namespace in C++ is used to organize code and avoid name conflicts, especially in large programs or when using multiple libraries.


πŸ”Ή 1. Why Use Namespaces?

  • Prevent name clashes

  • Organize large codebases

  • Improve readability and maintenance

  • Avoid global scope pollution

Example problem:

int count;

What if two libraries define count?
➑ Namespace solves this.


πŸ”Ή 2. Basic Namespace Syntax

namespace MyNamespace {
int x = 10;

void show() {
cout << "Hello from MyNamespace";
}
}

Access members:

cout << MyNamespace::x;
MyNamespace::show();

πŸ”Ή 3. Using using Keyword

Using Specific Members (Recommended)

using MyNamespace::x;
using MyNamespace::show;

cout << x;
show();


Using Entire Namespace ❌ (Not Recommended)

using namespace std;

βœ” Convenient for small programs
❌ Risky in large projects


πŸ”Ή 4. Standard Namespace (std)

Most C++ library features are inside std.

std::cout << "Hello";
std::vector<int> v;

πŸ”Ή 5. Nested Namespaces

namespace Company {
namespace Project {
void info() {
cout << "Project Info";
}
}
}

Access:

Company::Project::info();

C++17 Shortcut

namespace Company::Project {
void info() {}
}

πŸ”Ή 6. Anonymous Namespace

Used for file-level scope (internal linkage).

namespace {
int secret = 100;
}

βœ” Accessible only in that file
βœ” Alternative to static


πŸ”Ή 7. Namespace Aliasing

Shorten long namespace names.

namespace cp = Company::Project;
cp::info();

πŸ”Ή 8. Extending a Namespace

Namespaces can be split across multiple files.

namespace Math {
int add(int a, int b);
}
namespace Math {
int sub(int a, int b);
}

πŸ”Ή 9. Namespace vs Class

NamespaceClass
Organizes codeModels objects
No access specifiersHas access control
No instancesObjects created
Cannot be instantiatedCan be instantiated

❌ Common Mistakes

namespace std {
int x; // ❌ undefined behavior
}

Never add to std namespace.


πŸ“Œ Summary

  • Namespace avoids name conflicts

  • Use :: scope resolution operator

  • std is the standard namespace

  • Prefer specific using declarations

  • Anonymous namespaces limit file scope