C++ Namespaces

Namespaces in C++ are used to organize code into logical groups and to prevent name conflicts in large projects. They allow you to define identifiers (variables, functions, classes, etc.) under a named scope so that they don’t collide with identifiers in other parts of the program or other libraries.

Syntax

namespace NamespaceName {
    // Variables, functions, classes
}

Accessing Namespace Members

  • Namespaces prevent naming conflicts in large projects or when using multiple libraries.
  • The using namespace directive allows direct access but can lead to conflicts if overused.
  • Nested namespaces are supported in modern C++ for better organization.

Next Topic

Next, learn about Smart Pointers in C++.

  • Using the scope resolution operator :: (e.g., NamespaceName::variable).
  • Using the using namespace directive to avoid repeating the namespace (e.g., using namespace NamespaceName;).

Example: Basic Namespace

#include <iostream>
using namespace std;

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

    int multiply(int a, int b) {
        return a * b;
    }
}

int main() {
    // Accessing using scope resolution operator
    cout << "Sum: " << MyMath::add(5, 3) << endl;
    cout << "Product: " << MyMath::multiply(5, 3) << endl;

    return 0;
}

Output

Sum: 8
Product: 15

Example: Using using namespace

#include <iostream>
using namespace std;

namespace MyMath {
    int subtract(int a, int b) {
        return a - b;
    }
}

using namespace MyMath; // Allows direct access to namespace members

int main() {
    cout << "Difference: " << subtract(10, 4) << endl;
    return 0;
}

Output

Difference: 6

Important Notes

  • Namespaces prevent naming conflicts in large projects or when using multiple libraries.
  • The using namespace directive allows direct access but can lead to conflicts if overused.
  • Nested namespaces are supported in modern C++ for better organization.

Next Topic

Next, learn about Smart Pointers in C++.