Name Lookup

When the compiler reads an identifier, it must look up the identifier to determine which declaration it comes from. In most cases, you can readily tell which identifier is which, but it is not always so simple. A small mistake can sometimes lead to code that compiles successfully but runs incorrectly because an identifier refers to a different object from the one you intended. To understand name lookup fully, you must first understand namespaces (covered later in this chapter), functions (Chapter 5), classes (Chapter 6), and templates (Chapter 7).

Name lookup takes place before overloaded functions are resolved and before the access level of class members is checked. If a name is found in an inner scope, the compiler uses that declaration, even if a better declaration would be found in an outer scope. Example 2-3 shows how problems can arise when an overloaded function is declared in more than one namespace. The function func(int) is global, and func(double) is defined in namespace N. Inside call_func, the compiler looks up the name func by searching first in the local scope (that is, the function body), then in namespace N, where it finds func(double). Name lookup stops at that point because the compiler found a match. Therefore, func(3) converts 3 to type double and calls func(double). The main function brings all the overloaded func functions into its scope (with using declarations, which are described at the end of this chapter), so name lookup can find the best ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.