The scope of an identifier is the largest region of the program text in which the identifier can potentially be used to refer to its object. In C++, the object being referred to must be unique. However, the name to access the object, the identifier itself, can be reused. The meaning of the identifier depends upon the context in which the identifier is used. Scope is the general context used to distinguish the meanings of names.
The scope of an identifier is possibly noncontiguous. One of the ways that breakage occurs is when the same name is reused to declare a different entity, thereby creating a contained declarative region (inner) and a containing declarative region (outer). Thus, point of declaration is a factor affecting scope. Exploiting the possibility of a noncontiguous scope is the basis for the technique called information hiding.
The concept of scope that exists in C was expanded and refined in
C++. The following table shows the kinds of scopes and the minor
differences in terminology.
Kinds of scope | |
![]() |
![]() |
---|---|
block | local |
function | function |
function prototype | function prototype |
file (global) | global namespace |
namespace | |
class |
In all declarations, the identifier is in scope before the initializer. The following example demonstrates this:
int x; void f() { int x = x; }
The x declared in function f() has local scope, not global namespace scope.
The remainder of this section pertains to C++ only.
Global scope or global namespace scope is the outermost namespace scope of a program, in which objects, functions, types and templates can be defined. A user-defined namespace can be nested within the global scope using namespace definitions, and each user-defined namespace is a different scope, distinct from the global scope.
A function name that is first declared as a friend of a class is in the innermost nonclass scope that encloses the class. A function name that is first declared in an outer namespace will not be used as the friend declaration. For example,
int f(); namespace A { class X { friend f(); // refers to A::f() not to ::f(); } f() { /* definition of f() */ } }
If the friend function is a member of another class, it has the scope of that class. The scope of a class name first declared as a friend of a class is the first nonclass enclosing scope.
The implicit declaration of the class is not visible until another declaration of that same class is seen.
Related References