Lesson 33 +30 XP

Namespaces

Namespaces

Large programs combine code from many people and many libraries. If two libraries both define a function print() or a class List, the names collide and the program will not link.

A namespace is a named scope that groups related names, so that Graphics::draw and Printer::draw can coexist. Every standard library name lives in the namespace std, which is why our programs say using namespace std;.

1. Defining a Namespace

texttt{namespace} name { declarations of variables, functions, classes }

Note: no semicolon is needed after the closing brace (unlike a class).

C++
namespace TestSpace {
int m;
void display(int n) {
    cout << n;
}
}

A member is accessed from outside with the scope resolution operator: TestSpace::m = 100;.

2. Three Ways to Use a Namespace Member

WayExampleEffect
Qualified namestd::cout << x;uses one name once; always unambiguous
using declarationusing std::cout;brings one name into the current scope
using directiveusing namespace std;brings all names of the namespace into the current scope
C++
#include <iostream>

namespace Physics {
const double g = 9.8;
double weight(double mass) {
    return mass * g;
}
}

namespace Finance {
const double g = 0.18; // a different g: GST rate
double withTax(double price) {
    return price * (1 + g);
}
}

int main() {
    std::cout << "Physics::g = " << Physics::g << std::endl; // qualified names
    std::cout << "Finance::g = " << Finance::g << std::endl;

    using std::cout; // using declarations
    using std::endl;
    cout << "weight of 10 kg = " << Physics::weight(10) << " N" << endl;

    using namespace Finance;                                 // using directive
    cout << "price 500 with tax = " << withTax(500) << endl; // no Finance:: needed
    return 0;
}

Output:

OUTPUT
Physics::g = 9.8
Finance::g = 0.18
weight of 10 kg = 98 N
price 500 with tax = 590

Both namespaces define g without any conflict, because each g lives in its own namespace.

Ambiguity with using directives

If two using directives bring in the same name, using that name without qualification is ambiguous:

C++
using namespace Physics;
using namespace Finance;
// cout << g;          // error: reference to 'g' is ambiguous
cout << Physics::g; // OK: qualify it

So using namespace is convenient in small programs, but in large programs and especially in header files it should be avoided: it pulls every name into every file that includes the header.

3. Nested Namespaces

A namespace can be declared inside another. Members of the inner namespace are reached with two qualifiers.

C++
#include <iostream>
using namespace std;

namespace College {
const char* name = "IPU";
namespace CSE {
int seats = 120;
void info() {
    cout << name << " CSE seats: " << seats << endl;
} // outer names visible
}
namespace ECE {
int seats = 60;
}
}

int main() {
    College::CSE::info();
    cout << "ECE seats: " << College::ECE::seats << endl;
    using namespace College::CSE;
    cout << "seats (using CSE): " << seats << endl;
    return 0;
}

Output:

OUTPUT
IPU CSE seats: 120
ECE seats: 60
seats (using CSE): 120

4. Unnamed (Anonymous) Namespaces

A namespace without a name makes its members visible only in the file where it is declared. It replaces the C practice of declaring global variables and functions static to keep them private to a file.

C++
namespace {
int counter = 0; // usable only in this source file
void helper() {
    counter++;
}
}

5. Namespace Aliases

A long namespace name can be given a short alias:

C++
namespace CSE = College::CSE;
cout << CSE::seats;

6. Namespaces Are Open

A namespace can be extended later in the same file or in other files by writing another namespace block with the same name. This is how the standard library spreads std across many headers: <iostream>, <string> and <vector> all add names to the same std namespace.

C++
#include <iostream>
using namespace std;

namespace Shapes {
double square(double s) {
    return s * s;
}
}

// ... later, possibly in another file
namespace Shapes { // the same namespace, extended
double circle(double r) {
    return 3.14159 * r * r;
}
class Rectangle {
    double l, b;

public:
    Rectangle(double x, double y) : l(x), b(y) {}
    double area() const {
        return l * b;
    }
};
}

int main() {
    namespace S = Shapes; // alias
    S::Rectangle r(3, 4);
    cout << "square(5)   = " << S::square(5) << endl;
    cout << "circle(1)   = " << S::circle(1) << endl;
    cout << "rect area   = " << r.area() << endl;
    return 0;
}

Output:

OUTPUT
square(5)   = 25
circle(1)   = 3.14159
rect area   = 12

7. The std Namespace

Standard C++ places all library names (cout, cin, endl, string, vector, sort, exception and so on) in the namespace std. The new-style headers have no .h: <iostream>, <cstring>, <cmath>. The C headers are available as <cXXX> with their names in std too (<cstring>, <cstdlib>).

Old (pre-standard)Standard C++
#include <iostream.h>#include <iostream>
names are global: coutnames are in std: std::cout
#include <string.h>#include <cstring>

8. Advantages of Namespaces

  1. Avoid name collisions between libraries and between parts of a large program.
  2. Group logically related declarations under one name, documenting the program's structure.
  3. Allow file-private names through unnamed namespaces.
  4. Make it clear where a name comes from (Physics::g vs Finance::g).
💡 Tip

Key points to remember

  • namespace N { ... } (no semicolon) creates a named scope; use N::name to reach a member.
  • using N::name; brings one name in; using namespace N; brings all names in (risk of ambiguity).
  • Namespaces can be nested (A::B::x), aliased (namespace S = A::B;), unnamed (file-private) and extended later.
  • All standard library names live in std; standard headers have no .h.
  • Avoid using namespace in header files.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a namespace? How are namespace members accessed? Explain with a program. (5 Marks)
  • Write: the purpose (name collisions), the syntax, the three ways table, and the Physics/Finance program.
  • Q2. Explain nested namespaces, unnamed namespaces and namespace aliases. (5 Marks)
  • Q3. What is the std namespace? Why do we write using namespace std;? (2.5 Marks)
  • Q4. Differentiate between a using declaration and a using directive. (2.5 Marks)