Data
encapsulation
- Data encapsulation is a mechanism for bundling the data, and the functions that use it and data abstraction are a mechanism for exposing only the interfaces and hiding user details about the implementation.
- C++ data encapsulation is nothing more than a means of implementing data abstraction.
- Encapsulation is the process by which data and functions within a class are combined.
- This is equivalent to a capsule where several drugs are stored inside the capsule, thus keeping them from being ingested directly from outside.
- By default, all the members of a class are private, thereby preventing access from outside the class.
#include<iostream.h>
#include<conio.h>
class test
{
private:
int x;
public:
test(int a)
{
x =a;
}
int get()
{
return x;
}
};
int main()
{
test a(7);
cout<<"The Number is: "<<a.get();
return 0;
}
Expected Output:-
#include<iostream.h>
#include<conio.h>
#include<conio.h>
//More example of Encapsulation in C++
#include<iostream.h>
#include<conio.h>
#include<conio.h>
class test
{
private:
int x;
public:
test(int a)
{
x =a;
}
int get()
{
return x;
}
};
int main()
{
test a(7);
cout<<"The Number is: "<<a.get();
return 0;
}
Expected Output:-
// C++ program to explain Encapsulation
#include<conio.h>
class Encapsulation
{
private:
// data hidden from outside world
int x;
public:
// function to set value of
// variable x
void set(int a)
{
x =a;
}
// function to return value of
// variable x
int get()
{
return x;
}
};
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}
Expected Output:-
5
//Program to show Difference between Abstraction and Encapsulation in C++
#include<iostream.h>#include<conio.h>
class Summation {
private:
// private variables
int a, b, c;
public:
void sum(int x, int y)
{
a = x;
b = y;
c = a + b;
cout<<"Sum of the two number is : "<<c<<endl;
}
};
int main()
{
Summation s;
s.sum(5, 4);
return 0;
}
Expected Output:-
Sum of the two number is: 9
#include<iostream.h>
#include<conio.h>
class EncapsulationExample {
private:
// we declare a as private to hide it from outside
int a;
public:
// set() function to set the value of a
void set(int x)
{
a = x;
}
// get() function to return the value of a
int get()
{
return a;
}
};
// main function
int main()
{
EncapsulationExample e1;
e1.set(10);
cout<<e1.get();
return 0;
}
Expected Output:-
10
Tags:
c++ by mskuthar
Data encapsulation
Data encapsulation in C++.
manjeet singh kuthar
mskuthar
www.mskuthar.blogspot.com