Nested namespaces
- C++ course
- Beginner
- Lesson 109/116
- 5 min
Learn nested namespaces and their usage.
Nested namespaces
Namespaces can be nested; this is the basic way to split large systems into subcategories. To reach an inner namespace, you write a scope chain.
namespace app {
namespace util {
int helper() { return 7; }
}
}Here the helper function is in the app::util namespace. To call it, you write app::util::helper(). Since C++17, the shorthand namespace app::util { ... } is also available.
Nested using usage
You can import an entire nested namespace with using namespace app::util;. After this line, helper can be called directly.
using namespace app::util;
int n = helper(); // no app::util:: neededThis is convenient when you work a lot with a specific sub-namespace. Still, the risk of name clashes in large projects should not be forgotten; in doubt, the full name app::util::helper() is preferred.
Practice Define and call a nested namespace
Define namespace app { namespace util { int helper() { return 7; } } }. In main, call int n = app::util::helper();. Print with cout << n << endl;.
Starter code
#include <iostream>
using namespace std;
// Define app and util as nested namespaces
int main() {
// call the inner helper with its full name and print
return 0;
}Sample solution
#include <iostream>
using namespace std;
namespace app {
namespace util {
int helper() { return 7; }
}
}
int main() {
int n = app::util::helper();
cout << n << endl;
return 0;
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In namespace app { namespace util { ... } }, how is helper called?
- app.util.helper()
- app::util::helper() Correct answer
- app-helper()
- util::helper()
Explanation: Nested namespaces use :: chaining.
2 Fill in the blank: nested call
int n = app::util____helper();
int n = app::util::helper();
Explanation: The :: operator reaches the inner namespace.
3 Match each expression with its purpose
| Term | Meaning |
|---|---|
namespace app::util |
nested definition |
app::util::helper |
full call |
using namespace app::util |
imports |