Reputation: 21
Picking up programming after like 8 years of... not programming (starting college soon, brushing up on old knowledge).
What is the difference between scope and encapsulation? They seem to be rather similar.
Upvotes: 2
Views: 1750
Reputation: 385405
They are similar.
Scope is about defining the lifetime of objects (loosely related to the "lexical", or code-wise, boundaries of the place in which they were declared), whereas encapsulation is all about controlling who can access those objects during that lifetime.
Upvotes: 1
Reputation: 48665
A scope is an area within a program within which automatic variables may be created and at the end of which they are automatically destroyed. Examples are a function body or the code-block of a for-loop.
Scopes may enclose one another and variables in an outer scope may, or may not, be accessible by code in an inner scope.
For example the global scope encloses all other scopes and variables created in the global scope are visible to all other scopes (according to various name resolution rules).
Therefore scope also refers to the visibility of objects that can be accessed from a given point in the program.
There are different types of scope each with their own visibility rules, for example class scope refers to the visibility of member variables and member functions to the member functions of a class object.
For more detailed definitions see http://en.cppreference.com/w/cpp/language/scope
Encapsulation is when you hide the specific data that makes up an object and focus only on how the object behaves according to its function interface. In C++
this data hiding is primarily achieved by marking the data as private
or protected
rendering it inaccessible from outside the structure within which it is defined.
Upvotes: 3