In Object Oriented Programming, encapsulation represents binding data and functions into one container. This container hides the details of the data and the way functions process data.
In C++, Class is a container that binds data and functions. The mechanism of hiding details of a class is called abstraction and it is described in “C++ Abstraction”.
Class encapsulates all manipulations with the data. Take a look on the example:
class myStack { //interface of class myStack //this is only accessible for user public: //allocate memory for stack myStack(int _size = 50) { size = _size; stack = new int[size]; //initially stack is empty top = -1; } //add value to stack bool push(int i) { if (isFull()) return false; else { top++; stack[top] = i; } } int pop() { if (isEmpty()) throw new exception("Stack is empty"); else { return stack[top--]; } } //hidden data members and member functions private: //return true if stack is full bool isFull() { return size == top - 1; } bool isEmpty() { return top == -1; } int size; int* stack; int top; };
All functions and variables are inside myStack class. This means that myStack class encapsulates all the properties of the defined stack data structure. So from outside class, you can not perform any manipulations on stack pointer, its size or top data members. Only push, pop and create stack (using myStack()) functions will be visible to us because those are public.
Friend functions or friend classes reduces encapsulation. You have to write your classes as independent as possible and do not show any unnecessary information about class.
Encapsulation is the idea of hiding the details of how things are implemented without exposing full interface to the user. This allows the user to use the item without worrying about how it is implemented.
Access Functions
Encapsulation is achieved using access specifiers. In encapsulation we make all member variables private and provide public functions which allow user to work with the class. These functions are called as access functions. Access functions are used to return the value of private member variables. There are two types of access functions
- Getters: Functions which return the value of private member variables of the class.
- Setters: Functions which set the value of the private member variables of the class.
class Game { private: int m_Score; int m_Rank; public: // Getters int GetScore() { return m_Score; } int GetRank() { return m_Rank; } // Setters void SetScore(int iScore) { m_Score = iScore; } void SetRank(int iRank) { m_Rank = iRank; } };