skip to content

Namespaces and ADL

Namespaces prevent name clashes, using-declarations and directives pull names in, and argument-dependent lookup finds functions through their arguments. Interviewers ask why ADL exists.

on this pageshow

explore

questions

6

In C++, how does using std::cout; differ from using namespace std;, and why does the second not belong in a header?

level: juniorimportance: must knowfreq 72%

answer

  1. one name versus every name
  2. a declaration versus a lookup rule
  3. headers are pasted into includers
  4. ambiguity appears at the point of use

basics

~20 s

using std::cout; declares one name in the current scope; using namespace std; makes every std name visible to unqualified lookup. In a header the directive reaches every file that includes it, so names such as count become ambiguous there.

solid answer

~50 s

A **using-declaration** such as `using std::cout;` introduces exactly one name into the scope it appears in and behaves like a local declaration: it can hide an outer name, and it clashes at once with a local of the same name. A **using-directive** such as `using namespace std;` introduces no names; it tells unqualified lookup to treat every member of `std` as if declared in the nearest namespace enclosing both the directive and `std`, which for `std` is always the global namespace. At namespace scope in a header, that rule is pasted into every translation unit that includes the header, for the rest of that file. Any includer with its own `count`, `distance` or `data` then gets an `ambiguous` error at the point of use, far from the cause. Keep directives out of headers; in source files prefer using-declarations or a directive inside a function body.

code

cpp · 12 lines
cpp
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;   // imagine this line sits in a shared header

int count = 0;         // a global the application already had

int main() {
    std::vector<int> v{1, 2, 2, 3};
    count = static_cast<int>(std::count(v.begin(), v.end(), 2));
    std::cout << count << '\n';
}

go deeper

for a junior

Recall the two spellings and what each pulls in: one name for the declaration, the whole namespace for the directive. Say clearly that the directive never belongs at namespace scope in a header.

for a middle

Explain why: a directive introduces no names, it changes unqualified lookup, so conflicts appear only where an ambiguous name is used, in files that include the header and never chose the directive.

for a senior

Show you have debugged it: a build that broke when an unrelated header started including algorithm, a count or distance turned ambiguous, and the fix of qualifying names and moving directives into function bodies.

for a principal

Treat it as a header hygiene rule a team enforces with review and static checks, alongside qualified names in public headers and namespace aliases for long nested namespaces.

## Namespaces in one paragraph A **namespace** is a named scope for declarations. `std::vector` and a project's own `geo::vector` are different entities because their enclosing namespaces differ, and a **qualified name** such as `std::cout` says exactly which one you mean. Writing the qualifier everywhere is safe but verbose, so C++ offers two ways to drop it: the using-declaration and the using-directive. They look alike and behave very differently. ## The using-declaration: one name, as if declared here `using std::cout;` is a **declaration**. It introduces the single name `cout` into the scope where it appears, and from then on that name behaves much like a name declared in that scope: - In a block, it **hides** a same-named entity from an enclosing scope, for example a global `int count`. - If the same scope already declares an unrelated entity with that name, the program is ill-formed at the using-declaration itself; clang reports `target of using declaration conflicts with declaration already in scope`. - It names one thing (all overloads of a function name come along), so the rest of `std` stays out of reach. ## The using-directive: a rule for unqualified lookup `using namespace std;` is a **directive**, and the standard says outright that it does not introduce any names. Instead, during unqualified lookup after the directive, the members of `std` appear as if they were declared in the nearest enclosing namespace that contains both the directive and `std`. At file scope that is the global namespace. Two consequences follow: 1. Nothing conflicts at the directive line. A global `int count` and the function template `std::count` coexist until some expression says plain `count`. 2. At that point lookup finds both, and the use is ambiguous. The error appears wherever the name is used, which may be hundreds of lines and several files away from the directive. A directive may appear at namespace scope or in a block scope, but not in class scope. ## Why a header is the worst place for it `#include` pastes the header's text into the including file. A directive written at namespace scope in `geometry.hpp` therefore applies to every translation unit that includes `geometry.hpp`, directly or through another header, from that point to the end of the translation unit. Nobody who includes the header chose it, and nobody can undo it. ```cpp #include <algorithm> #include <vector> using namespace std; // arrived through a shared header int count = 0; // the application's own global int main() { std::vector<int> v{1, 2, 2, 3}; count = 2; // error: reference to 'count' is ambiguous } ``` Clang lists both candidates, the global `count` and `std::count` from `<algorithm>`. The same trap waits for any short common name in `std`: `distance`, `data`, `size`, `min`, `max`, `hash`, `function`. Whether a given name collides also depends on which standard headers happen to be included, so a build can break after an unrelated header starts including `<algorithm>`. | | `using std::cout;` | `using namespace std;` | |---|---|---| | What it is | a declaration of one name | a lookup rule for a whole namespace | | Names introduced | exactly one (all its overloads) | none | | Conflict with a local of the same name | error at the using-declaration | ambiguity only where the name is used | | Hides an outer name | yes, like any declaration | no | | In a header at namespace scope | still leaks one name to includers | leaks all of `std` to includers | | Allowed in class scope | yes, for base-class members | no | ## What to do instead - In headers, write qualified names: `std::vector<double>`, `std::size_t`. Readers of a header want the exact entity anyway. - In a `.cpp` file, a using-declaration for the few names you use often is the clean middle ground. - A directive inside a function body ends with that block, so its blast radius is one function. It is a reasonable convenience in short source files and tests, and still a bad idea in a header's inline functions. - For long namespaces, a **namespace alias** shortens the qualifier without changing lookup: `namespace fs = std::filesystem;`. The interview answer fits in two lines: a using-declaration declares one name; a using-directive changes how every unqualified name is looked up, and in a header it changes it for people who never asked.

  • Is using namespace std; acceptable inside a function body in a .cpp file?
    Usually yes. A directive in a block scope only affects unqualified lookup inside that block, so its effect ends at the closing brace and never reaches other files. It can still make a name ambiguous within that function if the file also declares a same-named entity, so many teams prefer a few using-declarations even there. The real rule is about headers and namespace scope.
  • What happens if a using-declaration names something that clashes with a local declaration in the same scope?
    The program is ill-formed at the using-declaration itself. Declaring int sort = 0; and then using std::sort; in the same block makes clang report "target of using declaration conflicts with declaration already in scope". That early, local error is one reason using-declarations are easier to live with than directives, whose conflicts surface only where an ambiguous name is used.
  • How do you shorten std::chrono::duration_cast without a using-directive?
    Use a namespace alias such as namespace chr = std::chrono; and write chr::duration_cast, or a using-declaration such as using std::chrono::duration_cast;. An alias changes no lookup rules, it only gives the namespace a shorter name, so it is safe even in a header if it lives inside your own namespace.

  • using namespace std copies every std name into the global namespace
  • A using-directive in a header only affects code written inside that header
  • using std::cout; makes the rest of iostream usable without std::
  • The compiler reports the conflict at the using namespace std line
  • If it compiles today, a using-directive in a header is harmless
open as a page

In C++, what is argument-dependent lookup, and why does std::cout << v need it to find an operator<< declared in v's namespace?

level: middleimportance: must knowfreq 62%

basics

~20 s

Argument-dependent lookup adds, for an unqualified function call, the functions declared in the namespaces of the argument types. It lets std::cout << v find geo::operator<< for a geo::Vec2 without a qualifier or a using-declaration at every call site.

open as a page

In C++, why does a derived class that declares scale(int) make the base class's scale(double) overloads uncallable through a derived object?

level: middleimportance: must knowfreq 58%

basics

~20 s

Name lookup stops at the first scope that declares the name, before overload resolution runs. The derived scale(int) hides every base scale, so a double argument is converted to int or the call fails. using Base::scale; restores them.

open as a page

In C++, what is a hidden friend operator, and why do library authors define operator== and operator<< that way?

level: seniorimportance: should knowfreq 32%

basics

~20 s

A hidden friend is a non-member function defined with friend inside a class body. Ordinary and qualified lookup cannot see it; only argument-dependent lookup finds it when the class is an argument, which keeps overload sets small and diagnostics short.

open as a page

In generic C++ code, why write using std::swap; swap(a, b); instead of std::swap(a, b), and what does C++20's std::ranges::swap change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A qualified std::swap(a, b) never sees a type's own cheaper swap. The two-step keeps std::swap as a fallback and lets argument-dependent lookup find a swap declared beside the type. C++20's std::ranges::swap does that lookup for you.

open as a page

In C++, how does an inline namespace let a library ship a new version of its types while users keep writing geo::Point?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Members of an inline namespace are used as if declared in the enclosing namespace, so geo::Point names geo::v2::Point. The version stays in mangled names, so code built against v1 and code built against v2 refer to different symbols for functions that use Point.

open as a page