Encapsulation in C++ and Real Life Example of Encapsulation in C++ - Encapsulation is a process of combining data members and functions in a single unit called class.
3. Sitesbay.com
Encapsulation in C++
Encapsulation is the method of combining the data and functions inside a class. Here we discuss
encapsulation in C++
Definition of Encapsulation in C++
Data Hiding is also known as Encapsulation. Encapsulation is the process of combining data and function
into a single unit called class. Data Hiding is the mechanism where the details of the class are hidden
from the user. The user can perform only a restricted set of operations in the hidden member of the
class.
Encapsulation is a powerful feature that leads to information hiding , abstract data type and friend
function. They encapsulate all the essential properties of the object that are to be created. Using the
method of encapsulation, the programmer cannot directly access the class. Encapsulation is a process of
combining data members and functions in a single unit called class.
Syntax of Encapsulation in C++
class class name
{
private:
datatype data;
public:
Member functions;
};
4. Sitesbay.com
Example of Encapsulation in C++
#include <iostream.h>
class Add
{
private:
int x,y,r;
public:
int Addition(int x, int y)
{
r= x+y;
return r;
}
void show( )
{ cout << "The sum is::" << r << "n";}
}s;
void main()
{
Add s;
s.Addition(10, 4);
s.show();
}
Output
The sum is:: 14
In the above encapsulation example the integer values "x,y,r" of the class "Add" can be accessed only
through the function "Addition". These integer values are encapsulated inside the class "Add".
5. Sitesbay.com
Real Life Example of Encapsulation in C++
Suppose you go to an automatic cola vending machine and request for a cola. The
machine processes your request and gives the cola.
Here automatic cola vending machine is a class. It contains both data i.e. Cola can and
operations i.e. service mechanism and they are wrapped/integrated under a single unit
Cola Vending Machine. This is called Encapsulation.
A Washing Machine and It's Power Button
What is the function that power button does? Switches the machine on (obviously). But
did u ever imagine the inside mechanism. Doesn't matter unless it's functioning well.
That's encapsulation. The object is wrapped and inner details are hidden. Only thing is
that object can be called and used. User friendly!
Advantage of Encapsulation in C++
The major benefit of data encapsulation is the security of the data. It protects the data
from unauthorized users that we inferred from the above stated real-real problem.