Encapsulation - Cmartinez-28/2143-OOP GitHub Wiki

Definition

Encapsulation is the grouping of data and the methods that put that data into a single unit known as a class. A class's data members are declared private by default, and must be specifically declared public or protected if that is what the user wants. These different options are known as access modifiers. Private members can be accessed by public getter/setter functions of the same class, or by using the friend keyword.

Purpose

Encapsulation allows a a class's data to be hidden and protected from outside methods. It also allows changes to internal implementation without affecting external code, and makes code easier to reuse and maintain.

Code Examples

Class Point
{
private:  //private by default, keyword not necessary
   int x,y;
public:
   void setX(int);
   void setY(int);
   int getX(int);   //private members can be accessed
   int getY(int);   //through public getters and setters
}
#Common Mistakes
* Overusing getters/setters
* Breaking encapsulation with inheritance
# Related Concepts
* Access Modifiers
* Classes
* Friend Keyword