It is merely a way to speed up compilation, since it allows the compiler to stop searching much earlier.
Basically, the search is done in a scope by scope basis, beginning with the inner scopes and ending with the outer scopes. The fact that inner objects hide outer objects is referred to as shadowing.
This is a bit complicated by the presence of another rule: ADL (Argument Dependent Lookup) which adds to the current scopes the scopes from which the arguments come from (apart from built-in).
It makes for a very complicated logic. Also there are ways to trump ADL...
So, a few examples:
Inner Scope prevail
void func(int i);
namespace N
{
void func(double d);
void dummy() { func(1); } // calls N::func
}
struct T
{
void func(char c);
void func(double d);
void dummy() { func(1); } // calls T::func (one of them, maybe ambiguity)
};
In both cases, it picks up the closer name.
With ADL
namespace N
{
struct T;
}
std::ostream& operator<<(std::ostream& out, N::T t);
namespace N
{
struct Custom;
std::ostream& operator<<(std::ostream& out, Custom c);
}
void funky()
{
N::T t;
std::cout << t << '\n'; // compilation fails,
// no suitable operator<< in either std:: or N::
}
Here the problem is that the list of functions considered does not contain the right operator because it hasn't been declared in one of the namespaces of its operands.
Mixing ADL and class
namespace N
{
struct T
{
T operator+(T const& rhs); // by the way, don't define +, -, etc... here ;)
};
T operator+(T const& lhs, T const& rhs);
}
N::T operator+(T const& lhs, T const& rhs);
Here we pick N::T::operator+(N::T const&) because it's member functions are preferred to free functions (most inner scope rule).