Namespace in C++ – Complete Notes
What is a Namespace?
A namespace in C++ is a container that holds a set of identifiers such as variables,
functions, and classes. It helps to organize code and avoid name conflicts.
Why Use Namespaces?
- Prevents naming conflicts in large programs
- Organizes code better
- Allows multiple libraries to define the same function or variable name without
conflict
Syntax of Namespace
namespace namespace_name {
// declarations
}
To access:
namespace_name::identifier;
Example 1: Basic Usage
#include <iostream>
using namespace std;
namespace myNamespace {
void display() {
cout << "Inside myNamespace!" << endl;
}
}
int main() {
myNamespace::display();
return 0;
}
Output:
Inside myNamespace!
Example 2: Avoiding Name Conflict
#include <iostream>
using namespace std;
void show() {
cout << "Global show()" << endl;
}
namespace demo {
void show() {
cout << "Namespace demo::show()" << endl;
}
}
int main() {
show(); // Global version
demo::show(); // Namespace version
return 0;
}
Using 'using' Keyword
You can avoid writing namespace_name:: again and again by using the using
keyword:
using namespace demo;
Now you can directly call show() if there's no conflict.
Nested Namespaces
namespace outer {
namespace inner {
void greet() {
cout << "Hello from inner namespace!" << endl;
}
}
}
int main() {
outer::inner::greet();
return 0;
}
Namespace Alias
namespace shortname = outer::inner;
int main() {
shortname::greet();
return 0;
}
Anonymous Namespace
Used when you want to keep things local to a file:
namespace {
void secret() {
cout << "Inside anonymous namespace" << endl;
}
}
Key Points:
- Namespaces help avoid naming conflicts
- Use scope resolution (::) to access namespace members
- 'using' makes access easier
- Nested, alias, and anonymous namespaces add flexibility