0
0
CppHow-ToBeginner · 3 min read

How to Create Namespace in C++: Syntax and Examples

In C++, you create a namespace using the syntax namespace name { /* code */ }. This groups related code under a name to avoid naming conflicts and organize your program.
📐

Syntax

The basic syntax to create a namespace in C++ is:

namespace name {
    // declarations and definitions
}

Here, name is the identifier for the namespace. Inside the braces, you put variables, functions, classes, or other code you want grouped.

cpp
namespace myNamespace {
    int value = 10;
    void greet() {
        std::cout << "Hello from myNamespace!" << std::endl;
    }
}
💻

Example

This example shows how to create a namespace and use its members with the scope resolution operator ::.

cpp
#include <iostream>

namespace math {
    int add(int a, int b) {
        return a + b;
    }
}

int main() {
    int result = math::add(5, 3);
    std::cout << "Result: " << result << std::endl;
    return 0;
}
Output
Result: 8
⚠️

Common Pitfalls

Common mistakes when using namespaces include:

  • Forgetting to use the scope resolution operator :: to access namespace members.
  • Using using namespace in global scope, which can cause name conflicts.
  • Defining the same namespace multiple times without understanding that they merge.

Example of wrong and right usage:

cpp
#include <iostream>

namespace example {
    void say() {
        std::cout << "Hello!" << std::endl;
    }
}

int main() {
    // Wrong: calling say() without namespace prefix
    // say(); // Error: 'say' was not declared in this scope

    // Right: use scope resolution
    example::say();
    return 0;
}
Output
Hello!
📊

Quick Reference

Summary tips for namespaces in C++:

  • Use namespaces to group related code and avoid name clashes.
  • Access members with namespace_name::member.
  • Use using namespace carefully to avoid conflicts.
  • Namespaces can be split across multiple files and merged.

Key Takeaways

Create a namespace using namespace name { /* code */ } to organize code.
Access namespace members with the scope resolution operator ::.
Avoid using using namespace globally to prevent name conflicts.
Namespaces can be extended by defining them multiple times in different places.
Namespaces help keep your code clean and prevent naming collisions.