using
- C++ course
- Beginner
- Lesson 107/116
- 4 min
Learn to import a namespace with using.
Importing with using
Writing ns::item at every call is sometimes verbose. The using directive makes all names in a namespace available at once.
using namespace math;
int n = add(2, 3); // no math:: neededHere, after using namespace math, add can be called directly. This is convenient in small programs; but it is used carefully in large projects because it can cause name clashes.
Risks of using
Although using namespace is handy, it has risks. If two namespaces contain a function with the same name, the call becomes ambiguous; this leads to a compile error.
For this reason, large projects usually avoid using namespace; instead they prefer full names like std::cout. Writing using in header files is almost always a bad practice; because everyone who includes that file automatically imports the namespace.
Practice Call add with using
Define namespace math { int add(int a, int b) { return a + b; } }. In main, first write using namespace math;, then call int n = add(4, 5);. Print with cout << n << endl;.
Starter code
#include <iostream>
using namespace std;
// Define the math namespace
int main() {
// import with using, call add, print
return 0;
}Sample solution
#include <iostream>
using namespace std;
namespace math {
int add(int a, int b) {
return a + b;
}
}
int main() {
using namespace math;
int n = add(4, 5);
cout << n << endl;
return 0;
}Expected output
9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: using directive
using ____ math;
int n = add(2, 3);
using namespace math;
int n = add(2, 3);
Explanation: using namespace math imports the namespace.
2 How is add(2,3) called after using namespace?
- math::add(2,3)
- namespace::add(2,3)
- math.add(2,3)
- add(2,3) Correct answer
Explanation: After using, you simply write add(2,3).
3 Match each expression with its result
| Term | Meaning |
|---|---|
using namespace math |
imports |
math::add |
call with full name |
using namespace std |
imports std |