Scope vs Visiblity vs Lifetime vs Accessibility vs etc

scopevariables

I have been trying to understand what it means to say "scope of a named entity". In reading about scope, there are terms like visibility, lifetime, accessibility and more that are used. What is confusing is the fact that the terms are at
times used distinctly and at times interchangeably.

Quoting from this IBM article:

scope is… the largest region in which the name potentially is valid.

Fair enough. But then what does this mean –

The visibility of an identifier is the region of program text from which the object associated with the identifier can be legally accessed.

Is visibility related to accessibility?

Further it goes on to say

Scope exceeds visibility when a duplicate identifier is used in an inner declarative region, thereby hiding the object declared in the outer declarative region. The original identifier cannot be used to access the first object until the scope of the duplicate identifier (the lifetime of the second object) has ended.

Does this mean scope and lifetime are the same things?

Do these terms like scope fundamentally mean the same thing in C++ as it does in say PHP or Python or even Java. Or they could mean different things conceptually depending on the language you are working in. The article I have quoted is C/C++ related, but I want to understand the terms in the general sense.

Best Answer

Scope, visibility and accessibility are all really talking about the same thing; given a particular declaration when can that declaration be referenced. Scope is the most general term and encompasses both visibility and accessibility and the referenced quote is adequate. Visibility and accessibility are usually applied to the members of a class as it is easier to think of them as being "hidden" or "not visible" as opposed to out of scope; that is, myMember is either private, protected or public controlling the visibility of the member in a class and its decedents. When inside a method of a class, all members are accessible or visible but only public members are from outside the class. protected members are only accessible or visible from the class itself or one of its derived classes. All of these contribute to the scope of myMember, that is the smallest region of text that can access myMember.

The parenthetical about lifetime is technically accurate for local variables but is really mixing a runtime concept, lifetime, with a compile-time or lexical concept, scope. You should ignore it. It is more confusing than helpful when trying to understand scope. Understanding lifetime is important to understand when a destructor is run and is related to scope but not important in understanding scope.

Related Topic