C++ Namespaces
In this page:
What is a Namespace?
A namespace is a feature in C++ used to group related code under a unique name. It helps prevent naming conflicts. This is especially useful when your project uses multiple external libraries with identical class or function names.
Example: What is a Namespace?
#include <iostream>
namespace MyLibrary {
void greet() { std::cout << "Hello from MyLibrary" << std::endl; }
}
int main() {
MyLibrary::greet();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Standard Namespace
All standard library templates, classes, and objects are grouped inside the std namespace. You can use the scope resolution operator or write a using directive to import standard elements into your current scope.
Example: The Standard Namespace
#include <iostream>
int main() {
std::cout << "Using the std namespace" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Namespaces
You can declare a namespace inside another namespace. This establishes a clear hierarchy for your code modules, similar to nested folders on your computer.
Example: Nested Namespaces
#include <iostream>
namespace Company {
namespace Project {
void run() { std::cout << "Running" << std::endl; }
}
}
int main() {
Company::Project::run();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Inline Namespaces
An inline namespace allows you to define versioned APIs. Members of an inline namespace are automatically visible in the parent namespace. This helps you deploy code updates while preserving backward compatibility.
Example: Inline Namespaces
#include <iostream>
namespace Library {
inline namespace V2 {
void greet() { std::cout << "Version 2" << std::endl; }
}
}
int main() {
Library::greet();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Namespaces Best Practices
Avoid putting global using directives in header files. This can pollute the global scope of any file that includes your header, leading to hard-to-track naming conflicts.
Example: Namespaces Best Practices
#include <iostream>
// Avoid "using namespace std;" in header files -- it would pollute the
// global scope of every file that includes this header.
int main() {
std::cout << "Prefer explicit std:: prefixes in headers" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 17 topics to unlock
0/17 topics done
Complete these topics first:
- C++ vs C Differences
- C++ Interview Questions
- C++ Debugging Techniques
- C++ Input Validation
- C++ Namespaces
- C++ Header Files
- C++ Multi-file Programming
- C++ static_cast
- C++ dynamic_cast
- C++ const_cast
- C++ reinterpret_cast
- C++ Threads (std::thread)
- C++ Mutex & Locks
- C++ async & future
- C++ Mini Project — Calculator
- C++ Mini Project — Student Management
- C++ Interview Questions Advanced