Namespaces &
std::
Learn how C++ organizes names into namespaces to avoid conflicts, and why the std:: prefix is the professional way to access the Standard Library.
What Is a Namespace?
A namespace is a named container that groups related identifiers: variables, functions, classes, and types. It prevents name collisions when two different libraries define things with the same name.
Why Do Namespaces Exist?
The std Namespace
The C++ Standard Library places every one of its identifiers inside a namespace called std (short for "standard"). This includes cout, cin, string, vector, sort, and thousands more.
Declaring a Namespace
int add(int a, int b) {
return a + b;
}
double pi = 3.14159;
}
The :: Scope Resolution Operator
The scope resolution operator (::) tells the compiler: "Look inside this namespace for this identifier." It is the precise, unambiguous way to access any name.
using namespace vs std::
Three Ways to Access std Names
How to Apply the std:: Prefix
Example 1: Hello World with std::
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Example 2: Multiple std Types
#include <string>
#include <vector>
int main() {
std::string name = "Alice";
std::vector<int> scores = {95, 87, 92};
std::cout << name << " has "
<< scores.size()
<< " scores." << std::endl;
return 0;
}
Example 3: Selective Using-Declaration
#include <string>
int main() {
using std::cout;
using std::endl;
using std::string;
string greeting = "Hi there!";
cout << greeting << endl;
return 0;
}
Creating Custom Namespaces
void draw() { /* draw a shape */ }
}
namespace audio {
void draw() { /* draw from audio buffer */ }
}
int main() {
graphics::draw(); // Unambiguous
audio::draw(); // Also unambiguous
}
How the Compiler Resolves Names
Common Mistakes
Comparison of Approaches
| std:: Prefix | using Declaration | using namespace | |
|---|---|---|---|
| Safety | Highest | Moderate | Lowest |
| Verbosity | More typing | Moderate | Least typing |
| In Headers? | ✓ Always safe | ✓ If inside function | ✕ Never |
| Collision Risk | None | Low | High |
| Best For | All projects | Repeated names | Tiny demos only |
Question 1 of 5
What does the :: operator do in std::cout?
Question 2 of 5
Why should you avoid writing using namespace std; in a header file?
Question 3 of 5
Consider the following code:
#include <iostream>
using std::cout;
int main() {
cout << "Hello" << endl;
}
This code will produce a compiler error. Which fix is correct?
Question 4 of 5
Two libraries each define a function called connect(). How do namespaces solve this?
Question 5 of 5
Which of the following is the safest way to use Standard Library names in a large project?