Every C++ program is the combination of data and functions. OOPs in C++ is mainly used for hiding data. This can be achieved using Encapsulation. Encapsulation in CPP goes a bit negative to Abstraction i.e.hide complexity.
Encapsulation can be defined as an act of combining properties and methods related to same object.
(Or)
Encapsulation is the definition of class which protectively wraps data and functions into a single unit. It is implemented using access specifiers public, private and protected.
Why Encapsulation?
Object becomes equipped with sufficient information set and set of operations.Any system can be assumed as collection of objects. These objects are capable of interacting with each other using various methods.
Using Encapsulation in CPP , internal representation of object cannot be seen by the end user. Encapsulation and Data hiding are same. Data hiding refers to hiding of details of class from the user.
As discussed private, public and protected are the access modifiers to make a data encapsulated.In order to work with classes containing access specifiers, a special function called "access function" is used and given below.
get() function: It returns values to private member functions of a class.
set() function: It sets the values to private member functions of class.
Example
[c]
#include<iostream>
using namespace std;
class square
{
private:
int side;
public:
void get()
{
cout <<"Enter value of side :"; cin >> side;
}
void Area()
{
cout << "Area of Square is:" << side*side;
}
};
int main()
{
square Obj;
Obj.get();
Obj.Area();
}
[/c]
Output
[c]
Enter value of side :8
Area of Square is:64[/c]
Advantages of Encapsulation
Advantages
As encapsulation does not disturb the interface, there is no chance for errors.
Application maintenance becomes easy and understand-ability increases.
Provides high-security.
Summary
Key Points
Class definition wrapping functions and data into a unit is called as Encapsulation in CPP.
Encapsulation in CPP is the complement of Abstraction.
Encapsulation is performed using accessing functions called as getc() and setc()
Programming
Tips
Using encapsulation, one can easily ping to other data types when needed. It can manipulate itself as per the changes made.